@widgetic/embed-sdk 2.0.17 → 2.1.0
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/README.md +26 -4
- package/dist/browser/chunks/ABTestManager.js +1 -1
- package/dist/browser/chunks/api.js +1 -1
- package/dist/browser/chunks/core.js +1 -1
- package/dist/browser/chunks/renderers.js +1 -1
- package/dist/browser/chunks/scanner.js +1 -1
- package/dist/browser/chunks/workflows.js +1 -0
- 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/api.js +1 -1
- package/dist/esm/chunks/core.js +1 -1
- package/dist/esm/chunks/renderers.js +1 -1
- package/dist/esm/chunks/scanner.js +1 -1
- package/dist/esm/chunks/workflows.js +1 -0
- package/dist/esm/embed-bootstrap.js +1 -1
- package/dist/esm/embed-sdk.js +1 -1
- package/dist/esm/types/abTesting/abVisitor.d.ts +2 -0
- package/dist/esm/types/core/autoscale-manager.d.ts +6 -0
- package/dist/esm/types/embed-sdk.d.ts +1 -0
- package/dist/esm/types/sdk/embed-sdk.d.ts +1 -0
- package/dist/esm/types/utils/declarative-embed-parser.d.ts +5 -0
- package/dist/esm/types/utils/host-workflow-watch.d.ts +62 -0
- package/dist/esm/types/utils/hydrate-published-host.d.ts +1 -0
- package/dist/esm/types/utils/mount-direct-widget.d.ts +12 -0
- package/dist/esm/types/utils/public-embed-lookup.d.ts +5 -0
- package/dist/esm/types/utils/published-host-bridge.d.ts +10 -0
- package/dist/esm/types/utils/workflow-code-loader.d.ts +14 -0
- package/dist/esm/types/utils/workflow-code-loader.umd.d.ts +32 -0
- package/dist/esm/types/utils/workflow-embed-registry.d.ts +15 -0
- package/dist/esm/types/utils/workflow-page-events.d.ts +41 -0
- package/dist/esm/types/utils/workflow-shared-contract.d.ts +35 -0
- package/dist/esm/types/utils/workflow-shared-services.d.ts +84 -0
- package/dist/esm/types/workflows/umd-entry.d.ts +1 -0
- package/dist/esm/types/workflows/visitor-position.d.ts +32 -0
- package/dist/esm/types/workflows/workflow-autoscale.d.ts +41 -0
- package/dist/esm/types/workflows/workflow-counts.d.ts +65 -0
- package/dist/esm/types/workflows/workflow-host.d.ts +71 -0
- package/dist/esm/types/workflows/workflow-lookup.d.ts +53 -0
- package/dist/esm/types/workflows/workflow-signals.d.ts +34 -0
- package/dist/esm/types/workflows/workflow-stage.d.ts +154 -0
- package/dist/umd/embed-bootstrap.js +1 -1
- package/dist/umd/embed-sdk-workflows.js +1 -0
- package/dist/umd/embed-sdk.js +1 -1
- package/package.json +2 -1
|
@@ -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-bootstrap"]={})}(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="",l=2500,c=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="50px",S=.1,C=3,A=3,E=1e3,R=10,x=5e3,M=36e5,W=6,D=!0,O=!0,L=!1,U="info",P="2.0.3",_="2.0.3";function z(){var e;return`${"undefined"!=typeof process&&"development"===(null===(e={NODE_ENV:"production"})||void 0===e?void 0:e.NODE_ENV)?q.DEV_API_URL:q.PROD_API_URL}${q.VERSION}`}const q={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},j="auto",$="inline",B="fixed",N=350,F=200,K=!1,H={CUSTOM_ELEMENTS:"undefined"!=typeof customElements,HTTP3:!1,RESIZE_OBSERVER:"undefined"!=typeof ResizeObserver},V=10,G=5e3,X=3;let Y=L;const J={get enabled(){return Y},logLevel:U},Q=["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 Z(e){if("string"==typeof e){const t=e.toLowerCase();for(const i of Q)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(Z);if("object"==typeof e){const t={};for(const[i,n]of Object.entries(e)){const e=i.toLowerCase();Q.some((t=>e.includes(t.toLowerCase())||e===t.toLowerCase()))&&"string"==typeof n&&n.length>0?t[i]=`[REDACTED_${n.length}_CHARS]`:t[i]=Z(n)}return t}return e}const ee=new class{constructor(e=J.logLevel){this.logLevels={debug:0,info:1,warn:2,error:3},this.currentLevel=this.logLevels[e]}shouldLog(e){return J.enabled&&this.logLevels[e]>=this.currentLevel}formatMessage(e,t,...i){const n=(new Date).toISOString();return[`${`[Widgetic SDK] [${e.toUpperCase()}] [${n}]`} ${t}`,...i.map(Z)]}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){Y=e}(e)}},te={debug:(e,...t)=>ee.debug(e,...t),info:(e,...t)=>ee.info(e,...t),warn:(e,...t)=>ee.warn(e,...t),error:(e,...t)=>ee.error(e,...t),setLevel:e=>ee.setLevel(e)};class ie{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 ne="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 oe="https://api.widgetic.com/v1".replace(/\/+$/,""),se="X-SDK-Version";class re{constructor(e){if(this.configuration={basePath:oe,headers:{},middleware:[]},"string"==typeof e){const t=(null==e?void 0:e.startsWith("Bearer "))?e.slice(7):e;this.configuration.apiKey=e=>ne(this,void 0,void 0,(function*(){return"authorization"===(null==e?void 0:e.toLowerCase())?`Bearer ${t}`:t})),this.configuration.accessToken=()=>ne(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||oe});if("string"==typeof e.accessToken&&e.accessToken){const t=e.accessToken,i=t.startsWith("Bearer ")?t.slice(7):t;this.configuration.apiKey=e=>ne(this,void 0,void 0,(function*(){return"authorization"===(null==e?void 0:e.toLowerCase())?`Bearer ${i}`:i})),this.configuration.accessToken=()=>ne(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:oe}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||he}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:()=>ne(this,void 0,void 0,(function*(){return e}))}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}}const ae=new re;class de{constructor(e=ae){this.configuration=e,this.fetchApi=(e,t)=>ne(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 ce(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 re)||(e=new re(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&&de.jsonRegex.test(e)}request(e,t){return ne(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 l="Response returned an error code",c=null;try{const e=yield d.json(),t=e.error,n=t&&"object"==typeof t?t.message:t;l=e.message||n||l;const o=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.code;"string"==typeof o&&o.length>0&&(c=o)}catch(e){try{l=yield d.text()}catch(e){l=a.statusText}}throw new le(a,l,c)}))}createFetchParams(e,t){return ne(this,void 0,void 0,(function*(){let i=(this.configuration.basePath||oe).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]:{}));Object.keys(n).some((e=>e.toLowerCase()===se.toLowerCase()))||(n[se]="@widgetic/api-sdk/1.0.42");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:()=>ne(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 l;l=a.body,d="undefined"!=typeof FormData&&l 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}}de.jsonRegex=new RegExp("^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$","i");class le extends Error{constructor(e,t,i=null){super(t),this.response=e,this.name="ResponseError",this.code=i}}class ce extends Error{constructor(e,t){super(t),this.cause=e,this.name="FetchError"}}class ue extends Error{constructor(e,t){super(t),this.field=e,this.name="RequiredError"}}function he(e,t=""){return Object.keys(e).map((i=>ge(i,e[i],t))).filter((e=>e.length>0)).join("&")}function ge(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 ge(e,Array.from(t),i)}return t instanceof Date?`${encodeURIComponent(n)}=${encodeURIComponent(t.toISOString())}`:t instanceof Object?he(t,n):`${encodeURIComponent(n)}=${encodeURIComponent(String(t))}`}class pe{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 ne(this,void 0,void 0,(function*(){const e=yield this.raw.json();return this.transformer(this.unwrapSuccessEnvelope(e))}))}}class me{constructor(e){this.raw=e}value(){return ne(this,void 0,void 0,(function*(){}))}}function fe(e){return function(e){if(null==e)return e;return{configured:e.configured,endpointId:null==e.endpointId?void 0:e.endpointId,url:null==e.url?void 0:e.url,createdAt:null==e.createdAt?void 0:new Date(e.createdAt),rotatedAt:null==e.rotatedAt?void 0:new Date(e.rotatedAt),previousSecretValidUntil:null==e.previousSecretValidUntil?void 0:new Date(e.previousSecretValidUntil),lastReceivedAt:null==e.lastReceivedAt?void 0:new Date(e.lastReceivedAt)}}(e)}function ve(e){return function(e){if(null==e)return e;return{configured:e.configured,endpointId:e.endpointId,url:e.url,secret:e.secret,createdAt:new Date(e.createdAt),rotatedAt:null==e.rotatedAt?void 0:new Date(e.rotatedAt),previousSecretValidUntil:null==e.previousSecretValidUntil?void 0:new Date(e.previousSecretValidUntil),lastReceivedAt:null==e.lastReceivedAt?void 0:new Date(e.lastReceivedAt)}}(e)}function ye(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,goalTarget:null==e.goalTarget?void 0:e.goalTarget,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 we(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(ye)}}(e)}function be(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 Ie(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 Te(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 ke(e){return function(e){if(null==e)return e;return{detected:null==e.detected?void 0:e.detected,pValue:null==e.pValue?void 0:e.pValue}}(e)}function Se(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,totalImpressionEvents:null==e.totalImpressionEvents?void 0:e.totalImpressionEvents,totalConversionEvents:null==e.totalConversionEvents?void 0:e.totalConversionEvents,counting:null==e.counting?void 0:e.counting,overallConversionRate:null==e.overallConversionRate?void 0:e.overallConversionRate,statisticalPower:null==e.statisticalPower?void 0:e.statisticalPower,sampleSizeNeededPerVariant:null==e.sampleSizeNeededPerVariant?void 0:e.sampleSizeNeededPerVariant,sampleRatioMismatch:null==e.sampleRatioMismatch?void 0:ke(e.sampleRatioMismatch),confidenceLevel:null==e.confidenceLevel?void 0:e.confidenceLevel}}(e)}function Ce(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,rawImpressions:null==e.rawImpressions?void 0:e.rawImpressions,rawConversions:null==e.rawConversions?void 0:e.rawConversions,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,significantlyWorse:null==e.significantlyWorse?void 0:e.significantlyWorse,bayesianProbabilityToBeatControl:null==e.bayesianProbabilityToBeatControl?void 0:e.bayesianProbabilityToBeatControl}}(e)}function Ae(e){return function(e){if(null==e)return e;return{overall:null==e.overall?void 0:Se(e.overall),variants:null==e.variants?void 0:e.variants.map(Ce),recommendation:null==e.recommendation?void 0:Te(e.recommendation)}}(e)}function Ee(e){return function(e){if(null==e)return e;return{id:e.id,title:e.title,status:e.status,charCount:e.charCount,chunkCount:e.chunkCount,createdAt:new Date(e.createdAt),readyAt:null==e.readyAt?null:new Date(e.readyAt)}}(e)}function Re(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 xe(e){return function(e){if(null==e)return e;return{documents:e.documents,characters:e.characters,maxDocuments:e.maxDocuments,maxTotalChars:e.maxTotalChars}}(e)}function Me(e){return function(e){if(null==e)return e;return{documents:e.documents.map(Ee),totals:xe(e.totals)}}(e)}function We(e){return function(e){if(null==e)return e;return{removed:e.removed}}(e)}function De(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 Oe(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 Le(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 Ue(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Le(e.data)}}(e)}function Pe(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,contentVersion:null==e.contentVersion?void 0:e.contentVersion,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,direct:null==e.direct?void 0:e.direct}}(e)}function _e(e){return function(e){if(null==e)return e;return{url:e.url,refreshSeconds:e.refreshSeconds}}(e)}function ze(e){return function(e){if(null==e)return e;return{name:e.name,type:e.type}}(e)}function qe(e){return function(e){if(null==e)return e;return{name:e.name,columns:e.columns.map(ze),rows:e.rows}}(e)}function je(e){return function(e){if(null==e)return e;return{compositionId:e.compositionId,hasData:e.hasData,tables:e.tables.map(qe)}}(e)}function $e(e){return function(e){if(null==e)return e;return{value:e.value,count:e.count}}(e)}function Be(e){return function(e){if(null==e)return e;return{group:null==e.group?void 0:e.group,count:null==e.count?void 0:e.count,avg:null==e.avg?void 0:e.avg,min:null==e.min?void 0:e.min,max:null==e.max?void 0:e.max,sum:null==e.sum?void 0:e.sum}}(e)}function Ne(e){return function(e){if(null==e)return e;return{column:e.column,tallies:e.tallies.map(Be),truncated:null==e.truncated?void 0:e.truncated}}(e)}function Fe(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($e),moreGroups:e.moreGroups,columns:e.columns,rows:null==e.rows?null:e.rows,moreRows:e.moreRows,aggregates:null==e.aggregates?void 0:Ne(e.aggregates)}}(e)}function Ke(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 He(e){return function(e){if(null==e)return e;return{path:e.path,message:e.message,expected:null==e.expected?void 0:e.expected,actual:null==e.actual?void 0:e.actual}}(e)}function Ve(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 Ge(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,contentVersion:null==e.contentVersion?void 0:e.contentVersion,validationResult:null==e.validationResult?void 0:Ve(e.validationResult),compositionUpdated:null==e.compositionUpdated?void 0:e.compositionUpdated,realtimeUpdateSent:null==e.realtimeUpdateSent?void 0:e.realtimeUpdateSent,item:null==e.item?void 0:e.item}}(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:be(e.data)}}(e)}function Ye(e){return function(e){if(null==e)return e;return{name:e.name,description:e.description,compositionId:e.compositionId,trafficPercentage:e.trafficPercentage,goalTarget:e.goalTarget}}(e,!1)}function Je(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(Ye),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 Qe(e){return function(e){if(null==e)return e;return{warnings:null==e.warnings?void 0:e.warnings}}(e)}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:Pe(e.data),meta:null==e.meta?void 0:Qe(e.meta)}}(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:Ge(e.data)}}(e)}function tt(e){return function(e){if(null==e)return e;return Object.assign(Object.assign({},e),{position:e.position})}(e,!1)}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}}(e)}function nt(e){return function(e){if(null==e)return e;return{warnings:null==e.warnings?void 0:e.warnings}}(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:Pe(e.data),meta:null==e.meta?void 0:nt(e.meta)}}(e)}function st(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,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,lastCommitSha:null==e.lastCommitSha?void 0:e.lastCommitSha,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 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:st(e.data),meta:null==e.meta?void 0:e.meta}}(e)}function at(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:ve(e.data)}}(e)}function dt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:we(e.data)}}(e)}function lt(e){return function(e){if(null==e)return e;return{deleted:null==e.deleted?void 0:e.deleted,contentVersion:null==e.contentVersion?void 0:e.contentVersion}}(e)}function ct(e){return function(e){if(null==e)return e;return{removed:e.removed}}(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:ct(e.data)}}(e)}function ht(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 gt(e){return function(e){if(null==e)return e;return{operationId:null==e.operationId?void 0:e.operationId}}(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:gt(e.data)}}(e)}function mt(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,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,lastCommitSha:null==e.lastCommitSha?void 0:e.lastCommitSha,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 ft(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:mt(e.data),warnings:null==e.warnings?void 0:e.warnings}}(e)}function vt(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 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{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,goal_target:null==e.goal_target?void 0:e.goal_target}}(e)}function bt(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(wt),success_metrics:null==e.success_metrics?void 0:e.success_metrics,primary_metric:null==e.primary_metric?void 0:e.primary_metric}}(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:Me(e.data)}}(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 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:e.data.map(Pe),meta:null==e.meta?void 0:Tt(e.meta)}}(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,tracking:null==e.tracking?void 0:e.tracking,supportsElementTarget:null==e.supportsElementTarget?void 0:e.supportsElementTarget,available:null==e.available?void 0:e.available,unavailableReason:null==e.unavailableReason?void 0:e.unavailableReason}}(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(St)}}(e)}function At(e){return function(e){if(null==e)return e;return{selector:null==e.selector?void 0:e.selector,label:null==e.label?void 0:e.label,kind:null==e.kind?void 0:e.kind,tag:null==e.tag?void 0:e.tag,metrics:null==e.metrics?void 0:e.metrics,preferred:null==e.preferred?void 0:e.preferred,matchCount:null==e.matchCount?void 0:e.matchCount}}(e)}function Et(e){return function(e){if(null==e)return e;return{metric:null==e.metric?void 0:e.metric,label:null==e.label?void 0:e.label,description:null==e.description?void 0:e.description,selector:null==e.selector?void 0:e.selector,recommended:null==e.recommended?void 0:e.recommended}}(e)}function Rt(e){return function(e){if(null==e)return e;return{compositionId:null==e.compositionId?void 0:e.compositionId,complete:null==e.complete?void 0:e.complete,note:null==e.note?void 0:e.note,goals:null==e.goals?void 0:e.goals.map(Et),targets:null==e.targets?void 0:e.targets.map(At)}}(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:Rt(e.data)}}(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:Pe(e.data)}}(e)}function Wt(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{success:null==e.success?void 0:e.success,data:null==e.data?void 0:e.data}}(e)}function Ot(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 Lt(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 Ut(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 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(Ke)}}(e)}function _t(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 zt(e){return function(e){if(null==e)return e;return{compositions:null==e.compositions?void 0:e.compositions.map(Pe),errors:null==e.errors?void 0:e.errors.map(_t)}}(e)}function qt(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 jt(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 $t(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(jt)}}(e)}function Bt(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 Nt(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(mt),meta:null==e.meta?void 0:Bt(e.meta)}}(e)}function Ft(e){return function(e){if(null==e)return e;return{widgets:null==e.widgets?void 0:e.widgets.map(mt),errors:null==e.errors?void 0:e.errors.map(_t)}}(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:fe(e.data)}}(e)}function Ht(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Ie(e.data)}}(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:Ae(e.data)}}(e)}function Gt(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 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(we),meta:null==e.meta?void 0:Gt(e.meta)}}(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:e.data}}(e)}function Jt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:We(e.data)}}(e)}function Qt(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 Zt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Qt(e.data)}}(e)}function ei(e){return function(e){if(null==e)return e;return{email:e.email}}(e,!1)}function ti(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 ii(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,contentVersion:null==e.contentVersion?void 0:e.contentVersion,validationResult:null==e.validationResult?void 0:ti(e.validationResult),compositionUpdated:null==e.compositionUpdated?void 0:e.compositionUpdated,realtimeUpdateSent:null==e.realtimeUpdateSent?void 0:e.realtimeUpdateSent}}(e)}function ni(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 oi(e){return function(e){if(null==e)return e;return{data:null==e.data?void 0:ni(e.data),message:null==e.message?void 0:e.message,warnings:null==e.warnings?void 0:e.warnings}}(e)}function si(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:oi(e.data)}}(e)}function ri(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:we(e.data),message:null==e.message?void 0:e.message}}(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:we(e.data),message:null==e.message?void 0:e.message}}(e)}function di(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 li(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,goal_target:e.goal_target,timestamp:null==e.timestamp?void 0:e.timestamp.toISOString(),user_id:e.user_id,session_id:e.session_id}}(e,!1)}function ci(e){return function(e){if(null==e)return e;return{event_type:e.event_type,data:li(e.data)}}(e,!1)}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,count:null==e.count?void 0:e.count}}(e)}function hi(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,goal_target:e.goal_target,user_id:e.user_id,session_id:e.session_id,timestamp:null==e.timestamp?void 0:e.timestamp.toISOString()}}(e,!1)}function gi(e){return function(e){if(null==e)return e;return{event_type:e.event_type,data:hi(e.data)}}(e,!1)}function pi(e){return function(e){if(null==e)return e;return{events:e.events.map(gi)}}(e,!1)}function mi(e){return function(e){if(null==e)return e;return{id:e.id,goalTarget:e.goalTarget}}(e,!1)}function fi(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,variants:null==e.variants?void 0:e.variants.map(mi),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 vi(e){return function(e){if(null==e)return e;return{token:e.token,email:e.email}}(e,!1)}function yi(e){return function(e){if(null==e)return e;return{repositoryId:null==e.repositoryId?void 0:e.repositoryId}}(e)}function wi(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:yi(e.data),meta:null==e.meta?void 0:e.meta}}(e)}function bi(e){return function(e){if(null==e)return e;return{thumbnailUrl:null==e.thumbnailUrl?void 0:e.thumbnailUrl}}(e)}function Ii(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:bi(e.data)}}(e)}function Ti(e){return function(e){if(null==e)return e;return{valid:e.valid,errors:null==e.errors?void 0:e.errors.map(He),warnings:null==e.warnings?void 0:e.warnings.map(He),sanitizedContent:null==e.sanitizedContent?void 0:e.sanitizedContent}}(e)}function ki(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 Si(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:ki(e.data)}}(e)}function Ci(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 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 Ei(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 Ri(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 xi(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(Ri),warnings:null==e.warnings?void 0:e.warnings.map(Ei)}}(e)}function Mi(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:xi(e.data)}}(e)}function Wi(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 Di(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(Wi),recommendations:null==e.recommendations?void 0:e.recommendations}}(e)}function Oi(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Di(e.data)}}(e)}function Li(e){return function(e){if(null==e)return e;return{composition_id:e.composition_id,name:e.name}}(e,!1)}function Ui(e){return function(e){if(null==e)return e;return{variants:e.variants.map(Li),success_metrics:e.success_metrics}}(e,!1)}function Pi(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(Ri),warnings:null==e.warnings?void 0:e.warnings.map(Ei)}}(e)}function _i(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Pi(e.data)}}(e)}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 de{assignVariantRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling assignVariant().');if(null==e.assignVariantRequest)throw new ue("assignVariantRequest",'Required parameter "assignVariantRequest" was null or undefined when calling assignVariant().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const 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 pe(n,(e=>ye(e)))}))}assignVariant(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.assignVariantRaw(e,t);return yield i.value()}))}checkWorkspaceABTestAutoStopRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling checkWorkspaceABTestAutoStop().');if(null==e.testId)throw new ue("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 pe(n,(e=>Ue(e)))}))}checkWorkspaceABTestAutoStop(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.checkWorkspaceABTestAutoStopRaw(e,t);return yield i.value()}))}createABTestAssignmentRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.createABTestAssignmentRequest)throw new ue("createABTestAssignmentRequest",'Required parameter "createABTestAssignmentRequest" was null or undefined when calling createABTestAssignment().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const 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 pe(n,(e=>Xe(e)))}))}createABTestAssignment(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.createABTestAssignmentRaw(e,t);return yield i.value()}))}createWorkspaceABConversionWebhookRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling createWorkspaceABConversionWebhook().');const i={};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:"/workspaces/{workspaceId}/ab-conversion-webhook".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"POST",headers:i,query:{}},t);return new pe(n,(e=>at(e)))}))}createWorkspaceABConversionWebhook(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.createWorkspaceABConversionWebhookRaw(e,t);return yield i.value()}))}createWorkspaceABTestRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling createWorkspaceABTest().');if(null==e.createABTestRequest)throw new ue("createABTestRequest",'Required parameter "createABTestRequest" was null or undefined when calling createWorkspaceABTest().');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:"/workspaces/{workspaceId}/ab-tests".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"POST",headers:i,query:{},body:Je(e.createABTestRequest)},t);return new pe(n,(e=>dt(e)))}))}createWorkspaceABTest(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.createWorkspaceABTestRaw(e,t);return yield i.value()}))}deleteWorkspaceABConversionWebhookRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling deleteWorkspaceABConversionWebhook().');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-conversion-webhook".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"DELETE",headers:i,query:{}},t);return new pe(n,(e=>ut(e)))}))}deleteWorkspaceABConversionWebhook(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.deleteWorkspaceABConversionWebhookRaw(e,t);return yield i.value()}))}deleteWorkspaceABTestRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling deleteWorkspaceABTest().');if(null==e.testId)throw new ue("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 pe(n,(e=>ht(e)))}))}deleteWorkspaceABTest(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.deleteWorkspaceABTestRaw(e,t);return yield i.value()}))}getABTestConfigRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 pe(i,(e=>bt(e)))}))}getABTestConfig(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.getABTestConfigRaw(e,t);return yield i.value()}))}getAvailableMetricsRaw(e){return zi(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 pe(i,(e=>Ct(e)))}))}getAvailableMetrics(e){return zi(this,void 0,void 0,(function*(){const t=yield this.getAvailableMetricsRaw(e);return yield t.value()}))}getCompositionABGoalTargetsRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling getCompositionABGoalTargets().');if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionABGoalTargets().');const i={};null!=e.metric&&(i.metric=e.metric);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}/compositions/{id}/ab-goal-targets".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))).replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:n,query:i},t);return new pe(o,(e=>xt(e)))}))}getCompositionABGoalTargets(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.getCompositionABGoalTargetsRaw(e,t);return yield i.value()}))}getVariantConfigRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 pe(i,(e=>qt(e)))}))}getVariantConfig(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.getVariantConfigRaw(e,t);return yield i.value()}))}getWorkspaceABConversionWebhookRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling getWorkspaceABConversionWebhook().');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-conversion-webhook".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"GET",headers:i,query:{}},t);return new pe(n,(e=>Kt(e)))}))}getWorkspaceABConversionWebhook(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.getWorkspaceABConversionWebhookRaw(e,t);return yield i.value()}))}getWorkspaceABTestRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling getWorkspaceABTest().');if(null==e.testId)throw new ue("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 pe(n,(e=>dt(e)))}))}getWorkspaceABTest(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.getWorkspaceABTestRaw(e,t);return yield i.value()}))}getWorkspaceABTestDiagnosisRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling getWorkspaceABTestDiagnosis().');if(null==e.testId)throw new ue("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 pe(n,(e=>Ht(e)))}))}getWorkspaceABTestDiagnosis(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.getWorkspaceABTestDiagnosisRaw(e,t);return yield i.value()}))}getWorkspaceABTestStatisticsRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling getWorkspaceABTestStatistics().');if(null==e.testId)throw new ue("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 pe(n,(e=>Vt(e)))}))}getWorkspaceABTestStatistics(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.getWorkspaceABTestStatisticsRaw(e,t);return yield i.value()}))}listWorkspaceABTestsRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("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 pe(o,(e=>Xt(e)))}))}listWorkspaceABTests(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.listWorkspaceABTestsRaw(e,t);return yield i.value()}))}pauseWorkspaceABTestRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling pauseWorkspaceABTest().');if(null==e.testId)throw new ue("testId",'Required parameter "testId" was null or undefined when calling pauseWorkspaceABTest().');const i={};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:"/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 pe(n,(e=>dt(e)))}))}pauseWorkspaceABTest(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.pauseWorkspaceABTestRaw(e,t);return yield i.value()}))}rotateWorkspaceABConversionWebhookSecretRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling rotateWorkspaceABConversionWebhookSecret().');const i={};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:"/workspaces/{workspaceId}/ab-conversion-webhook/rotate".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"POST",headers:i,query:{}},t);return new pe(n,(e=>at(e)))}))}rotateWorkspaceABConversionWebhookSecret(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.rotateWorkspaceABConversionWebhookSecretRaw(e,t);return yield i.value()}))}setWorkspaceABTestDurationRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling setWorkspaceABTestDuration().');if(null==e.testId)throw new ue("testId",'Required parameter "testId" was null or undefined when calling setWorkspaceABTestDuration().');if(null==e.setWorkspaceABTestDurationRequest)throw new ue("setWorkspaceABTestDurationRequest",'Required parameter "setWorkspaceABTestDurationRequest" was null or undefined when calling setWorkspaceABTestDuration().');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:"/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 pe(n,(e=>ri(e)))}))}setWorkspaceABTestDuration(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.setWorkspaceABTestDurationRaw(e,t);return yield i.value()}))}startWorkspaceABTestRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling startWorkspaceABTest().');if(null==e.testId)throw new ue("testId",'Required parameter "testId" was null or undefined when calling startWorkspaceABTest().');const i={};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:"/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 pe(n,(e=>dt(e)))}))}startWorkspaceABTest(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.startWorkspaceABTestRaw(e,t);return yield i.value()}))}stopWorkspaceABTestRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling stopWorkspaceABTest().');if(null==e.testId)throw new ue("testId",'Required parameter "testId" was null or undefined when calling stopWorkspaceABTest().');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:"/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 pe(n,(e=>ai(e)))}))}stopWorkspaceABTest(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.stopWorkspaceABTestRaw(e,t);return yield i.value()}))}trackABTestEventRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.trackABTestEventRequest)throw new ue("trackABTestEventRequest",'Required parameter "trackABTestEventRequest" was null or undefined when calling trackABTestEvent().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const n=yield this.request({path:"/ab-tests/analytics/events",method:"POST",headers:i,query:{},body:ci(e.trackABTestEventRequest)},t);return new pe(n,(e=>di(e)))}))}trackABTestEvent(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.trackABTestEventRaw(e,t);return yield i.value()}))}trackBulkABTestEventsRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.trackBulkABTestEventsRequest)throw new ue("trackBulkABTestEventsRequest",'Required parameter "trackBulkABTestEventsRequest" was null or undefined when calling trackBulkABTestEvents().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const n=yield this.request({path:"/ab-tests/analytics/bulk",method:"POST",headers:i,query:{},body:pi(e.trackBulkABTestEventsRequest)},t);return new pe(n,(e=>ui(e)))}))}trackBulkABTestEvents(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.trackBulkABTestEventsRaw(e,t);return yield i.value()}))}updateWorkspaceABTestRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling updateWorkspaceABTest().');if(null==e.testId)throw new ue("testId",'Required parameter "testId" was null or undefined when calling updateWorkspaceABTest().');if(null==e.updateABTestRequest)throw new ue("updateABTestRequest",'Required parameter "updateABTestRequest" was null or undefined when calling updateWorkspaceABTest().');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:"/workspaces/{workspaceId}/ab-tests/{testId}".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))).replace("{testId}",encodeURIComponent(String(e.testId))),method:"PUT",headers:i,query:{},body:fi(e.updateABTestRequest)},t);return new pe(n,(e=>dt(e)))}))}updateWorkspaceABTest(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.updateWorkspaceABTestRaw(e,t);return yield i.value()}))}validateWorkspaceCompositionDeletionRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling validateWorkspaceCompositionDeletion().');if(null==e.validateWorkspaceCompositionDeletionRequest)throw new ue("validateWorkspaceCompositionDeletionRequest",'Required parameter "validateWorkspaceCompositionDeletionRequest" was null or undefined when calling validateWorkspaceCompositionDeletion().');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:"/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 pe(n,(e=>Mi(e)))}))}validateWorkspaceCompositionDeletion(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.validateWorkspaceCompositionDeletionRaw(e,t);return yield i.value()}))}validateWorkspaceGoalTrackingRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling validateWorkspaceGoalTracking().');if(null==e.validateWorkspaceGoalTrackingRequest)throw new ue("validateWorkspaceGoalTrackingRequest",'Required parameter "validateWorkspaceGoalTrackingRequest" was null or undefined when calling validateWorkspaceGoalTracking().');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:"/workspaces/{workspaceId}/ab-tests/validate-goal-tracking".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"POST",headers:i,query:{},body:Ui(e.validateWorkspaceGoalTrackingRequest)},t);return new pe(n,(e=>Oi(e)))}))}validateWorkspaceGoalTracking(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.validateWorkspaceGoalTrackingRaw(e,t);return yield i.value()}))}validateWorkspaceWidgetDeletionRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling validateWorkspaceWidgetDeletion().');if(null==e.validateWorkspaceWidgetDeletionRequest)throw new ue("validateWorkspaceWidgetDeletionRequest",'Required parameter "validateWorkspaceWidgetDeletionRequest" was null or undefined when calling validateWorkspaceWidgetDeletion().');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:"/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 pe(n,(e=>_i(e)))}))}validateWorkspaceWidgetDeletion(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.validateWorkspaceWidgetDeletionRaw(e,t);return yield i.value()}))}}var ji="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 $i extends de{completeSignupRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.completeSignupRequest)throw new ue("completeSignupRequest",'Required parameter "completeSignupRequest" was null or undefined when calling completeSignup().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const 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 me(n)}))}completeSignup(e,t){return ji(this,void 0,void 0,(function*(){yield this.completeSignupRaw(e,t)}))}confirmEmailRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.updateEmailRequest)throw new ue("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:vi(e.updateEmailRequest)},t);return new me(n)}))}confirmEmail(e,t){return ji(this,void 0,void 0,(function*(){yield this.confirmEmailRaw(e,t)}))}consumeOAuthSessionBridgeRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.bridgeId)throw new ue("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 me(i)}))}consumeOAuthSessionBridge(e,t){return ji(this,void 0,void 0,(function*(){yield this.consumeOAuthSessionBridgeRaw(e,t)}))}deleteAccountRaw(e,t){return ji(this,void 0,void 0,(function*(){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:"/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 me(n)}))}deleteAccount(){return ji(this,arguments,void 0,(function*(e={},t){yield this.deleteAccountRaw(e,t)}))}getSessionRaw(e){return ji(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 me(i)}))}getSession(e){return ji(this,void 0,void 0,(function*(){yield this.getSessionRaw(e)}))}getUserMetadataRaw(e){return ji(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 me(i)}))}getUserMetadata(e){return ji(this,void 0,void 0,(function*(){yield this.getUserMetadataRaw(e)}))}initiateOAuthRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.provider)throw new ue("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 me(n)}))}initiateOAuth(e,t){return ji(this,void 0,void 0,(function*(){yield this.initiateOAuthRaw(e,t)}))}loginUserRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.loginUserRequest)throw new ue("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 pe(n,(e=>Yt(e)))}))}loginUser(e,t){return ji(this,void 0,void 0,(function*(){const i=yield this.loginUserRaw(e,t);return yield i.value()}))}logoutUserRaw(e){return ji(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 me(i)}))}logoutUser(e){return ji(this,void 0,void 0,(function*(){yield this.logoutUserRaw(e)}))}refreshSessionRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.refreshSessionRequest)throw new ue("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 me(n)}))}refreshSession(e,t){return ji(this,void 0,void 0,(function*(){yield this.refreshSessionRaw(e,t)}))}resendConfirmationRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.resetPasswordRequest)throw new ue("resetPasswordRequest",'Required parameter "resetPasswordRequest" was null or undefined when calling resendConfirmation().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const n=yield this.request({path:"/auth/resend-confirmation",method:"POST",headers:i,query:{},body:ei(e.resetPasswordRequest)},t);return new me(n)}))}resendConfirmation(e,t){return ji(this,void 0,void 0,(function*(){yield this.resendConfirmationRaw(e,t)}))}resetPasswordRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.resetPasswordRequest)throw new ue("resetPasswordRequest",'Required parameter "resetPasswordRequest" was null or undefined when calling resetPassword().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const n=yield this.request({path:"/auth/reset-password",method:"POST",headers:i,query:{},body:ei(e.resetPasswordRequest)},t);return new me(n)}))}resetPassword(e,t){return ji(this,void 0,void 0,(function*(){yield this.resetPasswordRaw(e,t)}))}signupUserRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.signupUserRequest)throw new ue("signupUserRequest",'Required parameter "signupUserRequest" was null or undefined when calling signupUser().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const 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 me(n)}))}signupUser(e,t){return ji(this,void 0,void 0,(function*(){yield this.signupUserRaw(e,t)}))}signupWithInvitationRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.signupWithInvitationRequest)throw new ue("signupWithInvitationRequest",'Required parameter "signupWithInvitationRequest" was null or undefined when calling signupWithInvitation().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const 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 me(n)}))}signupWithInvitation(e,t){return ji(this,void 0,void 0,(function*(){yield this.signupWithInvitationRaw(e,t)}))}updateEmailRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.updateEmailRequest)throw new ue("updateEmailRequest",'Required parameter "updateEmailRequest" was null or undefined when calling updateEmail().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const n=yield this.request({path:"/auth/update-email",method:"POST",headers:i,query:{},body:vi(e.updateEmailRequest)},t);return new me(n)}))}updateEmail(e,t){return ji(this,void 0,void 0,(function*(){yield this.updateEmailRaw(e,t)}))}updateNameRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.updateNameRequest)throw new ue("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 me(n)}))}updateName(e,t){return ji(this,void 0,void 0,(function*(){yield this.updateNameRaw(e,t)}))}updatePasswordRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.updatePasswordRequest)throw new ue("updatePasswordRequest",'Required parameter "updatePasswordRequest" was null or undefined when calling updatePassword().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const 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 me(n)}))}updatePassword(e,t){return ji(this,void 0,void 0,(function*(){yield this.updatePasswordRaw(e,t)}))}updateUserMetadataRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.updateUserMetadataRequest)throw new ue("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 me(n)}))}updateUserMetadata(e,t){return ji(this,void 0,void 0,(function*(){yield this.updateUserMetadataRaw(e,t)}))}validateInviteCodeRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.code)throw new ue("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 pe(n,(e=>Si(e)))}))}validateInviteCode(e,t){return ji(this,void 0,void 0,(function*(){const i=yield this.validateInviteCodeRaw(e,t);return yield i.value()}))}}var Bi="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 Ni extends de{addAiAnswersKnowledgeDocumentRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling addAiAnswersKnowledgeDocument().');if(null==e.addAiAnswersKnowledgeDocumentRequest)throw new ue("addAiAnswersKnowledgeDocumentRequest",'Required parameter "addAiAnswersKnowledgeDocumentRequest" was null or undefined when calling addAiAnswersKnowledgeDocument().');const i={"Content-Type":"application/json"};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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}/adapters/ai-answers/knowledge/documents".replace("{id}",encodeURIComponent(String(e.id))),method:"POST",headers:i,query:{},body:(s=e.addAiAnswersKnowledgeDocumentRequest,o=s,null==o?o:{title:o.title,text:o.text})},t);var o,s;return new pe(n,(e=>Re(e)))}))}addAiAnswersKnowledgeDocument(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.addAiAnswersKnowledgeDocumentRaw(e,t);return yield i.value()}))}checkCompositionAccessRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 pe(n,(e=>De(e)))}))}checkCompositionAccess(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.checkCompositionAccessRaw(e,t);return yield i.value()}))}createCompositionContentItemRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling createCompositionContentItem().');if(null==e.list)throw new ue("list",'Required parameter "list" was null or undefined when calling createCompositionContentItem().');if(null==e.createCompositionContentItemRequest)throw new ue("createCompositionContentItemRequest",'Required parameter "createCompositionContentItemRequest" was null or undefined when calling createCompositionContentItem().');const i={"Content-Type":"application/json"};if(null!=e.ifMatch&&(i["If-Match"]=String(e.ifMatch)),null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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/{list}/items".replace("{id}",encodeURIComponent(String(e.id))).replace("{list}",encodeURIComponent(String(e.list))),method:"POST",headers:i,query:{},body:tt(e.createCompositionContentItemRequest)},t);return new pe(n,(e=>et(e)))}))}createCompositionContentItem(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.createCompositionContentItemRaw(e,t);return yield i.value()}))}createCompositionDatabaseRecordRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling createCompositionDatabaseRecord().');if(null==e.table)throw new ue("table",'Required parameter "table" was null or undefined when calling createCompositionDatabaseRecord().');if(null==e.body)throw new ue("body",'Required parameter "body" was null or undefined when calling createCompositionDatabaseRecord().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>it(e)))}))}createCompositionDatabaseRecord(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.createCompositionDatabaseRecordRaw(e,t);return yield i.value()}))}createCompositionRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.newComposition)throw new ue("newComposition",'Required parameter "newComposition" was null or undefined when calling createComposition().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Ze(e)))}))}createComposition(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.createCompositionRaw(e,t);return yield i.value()}))}deleteCompositionContentItemRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling deleteCompositionContentItem().');if(null==e.list)throw new ue("list",'Required parameter "list" was null or undefined when calling deleteCompositionContentItem().');if(null==e.itemId)throw new ue("itemId",'Required parameter "itemId" was null or undefined when calling deleteCompositionContentItem().');const i={};if(null!=e.ifMatch&&(i["If-Match"]=String(e.ifMatch)),null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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/{list}/items/{itemId}".replace("{id}",encodeURIComponent(String(e.id))).replace("{list}",encodeURIComponent(String(e.list))).replace("{itemId}",encodeURIComponent(String(e.itemId))),method:"DELETE",headers:i,query:{}},t);return new pe(n,(e=>lt(e)))}))}deleteCompositionContentItem(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.deleteCompositionContentItemRaw(e,t);return yield i.value()}))}deleteCompositionDataSourceRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling deleteCompositionDataSource().');const i={};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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}/data-source".replace("{id}",encodeURIComponent(String(e.id))),method:"DELETE",headers:i,query:{}},t);return new pe(n,(e=>function(e){return null==e?e:{removed:e.removed}}(e)))}))}deleteCompositionDataSource(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.deleteCompositionDataSourceRaw(e,t);return yield i.value()}))}deleteCompositionDatabaseRecordRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling deleteCompositionDatabaseRecord().');if(null==e.table)throw new ue("table",'Required parameter "table" was null or undefined when calling deleteCompositionDatabaseRecord().');if(null==e.recordId)throw new ue("recordId",'Required parameter "recordId" was null or undefined when calling deleteCompositionDatabaseRecord().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>it(e)))}))}deleteCompositionDatabaseRecord(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.deleteCompositionDatabaseRecordRaw(e,t);return yield i.value()}))}deleteCompositionRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling deleteComposition().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 me(n)}))}deleteComposition(e,t){return Bi(this,void 0,void 0,(function*(){yield this.deleteCompositionRaw(e,t)}))}describeCompositionEntriesRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling describeCompositionEntries().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>je(e)))}))}describeCompositionEntries(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.describeCompositionEntriesRaw(e,t);return yield i.value()}))}duplicateCompositionRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling duplicateComposition().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>pt(e)))}))}duplicateComposition(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.duplicateCompositionRaw(e,t);return yield i.value()}))}getAiAnswersKnowledgeRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getAiAnswersKnowledge().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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}/adapters/ai-answers/knowledge".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new pe(n,(e=>It(e)))}))}getAiAnswersKnowledge(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.getAiAnswersKnowledgeRaw(e,t);return yield i.value()}))}getAllCompositionsRaw(e,t){return Bi(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.widgetId=e.widgetId),null!=e.workspace&&(i.workspace=e.workspace),null!=e.projectFolder&&(i.projectFolder=e.projectFolder),null!=e.status&&(i.status=e.status),null!=e.managedUserId&&(i.managedUserId=e.managedUserId),null!=e.managedUserExternalId&&(i.managedUserExternalId=e.managedUserExternalId);const n={};if(null!=e.xManagedUserId&&(n["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(n["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(o,(e=>kt(e)))}))}getAllCompositions(){return Bi(this,arguments,void 0,(function*(e={},t){const i=yield this.getAllCompositionsRaw(e,t);return yield i.value()}))}getCompositionByIdRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionById().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Mt(e)))}))}getCompositionById(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.getCompositionByIdRaw(e,t);return yield i.value()}))}getCompositionContentSchemaRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionContentSchema().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Wt(e)))}))}getCompositionContentSchema(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.getCompositionContentSchemaRaw(e,t);return yield i.value()}))}getCompositionContentRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionContent().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n)}))}getCompositionContent(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.getCompositionContentRaw(e,t);return yield i.value()}))}getCompositionDataSourceRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionDataSource().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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}/data-source".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new pe(n,(e=>_e(e)))}))}getCompositionDataSource(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.getCompositionDataSourceRaw(e,t);return yield i.value()}))}getCompositionDatabaseRecordRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionDatabaseRecord().');if(null==e.table)throw new ue("table",'Required parameter "table" was null or undefined when calling getCompositionDatabaseRecord().');if(null==e.recordId)throw new ue("recordId",'Required parameter "recordId" was null or undefined when calling getCompositionDatabaseRecord().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>it(e)))}))}getCompositionDatabaseRecord(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.getCompositionDatabaseRecordRaw(e,t);return yield i.value()}))}getCompositionDatabaseRecordsRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionDatabaseRecords().');if(null==e.table)throw new ue("table",'Required parameter "table" was null or undefined when calling getCompositionDatabaseRecords().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Dt(e)))}))}getCompositionDatabaseRecords(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.getCompositionDatabaseRecordsRaw(e,t);return yield i.value()}))}getCompositionDesignSchemaRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionDesignSchema().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Ot(e)))}))}getCompositionDesignSchema(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.getCompositionDesignSchemaRaw(e,t);return yield i.value()}))}getCompositionDesignRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionDesign().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n)}))}getCompositionDesign(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.getCompositionDesignRaw(e,t);return yield i.value()}))}getCompositionEmbedSchemaRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionEmbedSchema().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Lt(e)))}))}getCompositionEmbedSchema(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.getCompositionEmbedSchemaRaw(e,t);return yield i.value()}))}getCompositionEmbedSettingsRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionEmbedSettings().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n)}))}getCompositionEmbedSettings(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.getCompositionEmbedSettingsRaw(e,t);return yield i.value()}))}getCompositionPreviewRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionPreview().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Ut(e)))}))}getCompositionPreview(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.getCompositionPreviewRaw(e,t);return yield i.value()}))}getCompositionVersionsRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionVersions().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Pt(e)))}))}getCompositionVersions(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.getCompositionVersionsRaw(e,t);return yield i.value()}))}getCompositionsBatchRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.getCompositionsBatchRequest)throw new ue("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 pe(n,(e=>zt(e)))}))}getCompositionsBatch(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.getCompositionsBatchRaw(e,t);return yield i.value()}))}patchCompositionContentItemRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling patchCompositionContentItem().');if(null==e.list)throw new ue("list",'Required parameter "list" was null or undefined when calling patchCompositionContentItem().');if(null==e.itemId)throw new ue("itemId",'Required parameter "itemId" was null or undefined when calling patchCompositionContentItem().');if(null==e.requestBody)throw new ue("requestBody",'Required parameter "requestBody" was null or undefined when calling patchCompositionContentItem().');const i={"Content-Type":"application/json"};if(null!=e.ifMatch&&(i["If-Match"]=String(e.ifMatch)),null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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/{list}/items/{itemId}".replace("{id}",encodeURIComponent(String(e.id))).replace("{list}",encodeURIComponent(String(e.list))).replace("{itemId}",encodeURIComponent(String(e.itemId))),method:"PATCH",headers:i,query:{},body:e.requestBody},t);return new pe(n,(e=>et(e)))}))}patchCompositionContentItem(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.patchCompositionContentItemRaw(e,t);return yield i.value()}))}readCompositionEntriesRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling readCompositionEntries().');if(null==e.table)throw new ue("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),null!=e.aggregate&&(i.aggregate=e.aggregate),null!=e.column&&(i.column=e.column),null!=e.since&&(i.since=e.since.toISOString()),null!=e.until&&(i.until=e.until.toISOString()),null!=e.context&&(i.context=e.context),null!=e.filter&&(i.filter=e.filter);const n={};if(null!=e.xManagedUserId&&(n["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(n["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(o,(e=>Fe(e)))}))}readCompositionEntries(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.readCompositionEntriesRaw(e,t);return yield i.value()}))}removeAiAnswersKnowledgeDocumentRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling removeAiAnswersKnowledgeDocument().');if(null==e.documentId)throw new ue("documentId",'Required parameter "documentId" was null or undefined when calling removeAiAnswersKnowledgeDocument().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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}/adapters/ai-answers/knowledge/documents/{documentId}".replace("{id}",encodeURIComponent(String(e.id))).replace("{documentId}",encodeURIComponent(String(e.documentId))),method:"DELETE",headers:i,query:{}},t);return new pe(n,(e=>Jt(e)))}))}removeAiAnswersKnowledgeDocument(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.removeAiAnswersKnowledgeDocumentRaw(e,t);return yield i.value()}))}setCompositionDataSourceRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling setCompositionDataSource().');if(null==e.setCompositionDataSourceRequest)throw new ue("setCompositionDataSourceRequest",'Required parameter "setCompositionDataSourceRequest" was null or undefined when calling setCompositionDataSource().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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}/data-source".replace("{id}",encodeURIComponent(String(e.id))),method:"PUT",headers:i,query:{},body:(s=e.setCompositionDataSourceRequest,o=s,null==o?o:{url:o.url,refreshSeconds:o.refreshSeconds})},t);var o,s;return new pe(n,(e=>_e(e)))}))}setCompositionDataSource(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.setCompositionDataSourceRaw(e,t);return yield i.value()}))}setDynamicContentRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling setDynamicContent().');if(null==e.setDynamicContentRequest)throw new ue("setDynamicContentRequest",'Required parameter "setDynamicContentRequest" was null or undefined when calling setDynamicContent().');const i={"Content-Type":"application/json"};if(null!=e.ifMatch&&(i["If-Match"]=String(e.ifMatch)),null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>ii(e)))}))}setDynamicContent(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.setDynamicContentRaw(e,t);return yield i.value()}))}updateCompositionDatabaseRecordRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling updateCompositionDatabaseRecord().');if(null==e.table)throw new ue("table",'Required parameter "table" was null or undefined when calling updateCompositionDatabaseRecord().');if(null==e.recordId)throw new ue("recordId",'Required parameter "recordId" was null or undefined when calling updateCompositionDatabaseRecord().');if(null==e.body)throw new ue("body",'Required parameter "body" was null or undefined when calling updateCompositionDatabaseRecord().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>it(e)))}))}updateCompositionDatabaseRecord(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.updateCompositionDatabaseRecordRaw(e,t);return yield i.value()}))}updateCompositionStatusRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling updateCompositionStatus().');if(null==e.updateCompositionStatusRequest)throw new ue("updateCompositionStatusRequest",'Required parameter "updateCompositionStatusRequest" was null or undefined when calling updateCompositionStatus().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Pe(e)))}))}updateCompositionStatus(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.updateCompositionStatusRaw(e,t);return yield i.value()}))}updateCompositionRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling updateComposition().');if(null==e.updateComposition)throw new ue("updateComposition",'Required parameter "updateComposition" was null or undefined when calling updateComposition().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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,databaseSchema:o.databaseSchema,projectId:o.projectId})},t);var o,s;return new pe(n,(e=>Mt(e)))}))}updateComposition(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.updateCompositionRaw(e,t);return yield i.value()}))}validateCompositionContentRaw(e,t){return Bi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling validateCompositionContent().');if(null==e.requestBody)throw new ue("requestBody",'Required parameter "requestBody" was null or undefined when calling validateCompositionContent().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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.requestBody},t);return new pe(n,(e=>Ti(e)))}))}validateCompositionContent(e,t){return Bi(this,void 0,void 0,(function*(){const i=yield this.validateCompositionContentRaw(e,t);return yield i.value()}))}}var Fi="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 Ki extends de{exchangeTokenRaw(e,t){return Fi(this,void 0,void 0,(function*(){if(null==e.exchangeTokenRequest)throw new ue("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 pe(n,(e=>yt(e)))}))}exchangeToken(e,t){return Fi(this,void 0,void 0,(function*(){const i=yield this.exchangeTokenRaw(e,t);return yield i.value()}))}validateTokenRaw(e){return Fi(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 pe(i,(e=>Ai(e)))}))}validateToken(e){return Fi(this,void 0,void 0,(function*(){const t=yield this.validateTokenRaw(e);return yield t.value()}))}}var Hi="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 Vi extends de{checkWidgetAccessRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 pe(n,(e=>Oe(e)))}))}checkWidgetAccess(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.checkWidgetAccessRaw(e,t);return yield i.value()}))}createCompositionFromWidgetRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling createCompositionFromWidget().');if(null==e.createCompositionFromWidgetRequest)throw new ue("createCompositionFromWidgetRequest",'Required parameter "createCompositionFromWidgetRequest" was null or undefined when calling createCompositionFromWidget().');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/{id}/composition".replace("{id}",encodeURIComponent(String(e.id))),method:"POST",headers:i,query:{},body:(s=e.createCompositionFromWidgetRequest,o=s,null==o?o:{name:o.name,content:o.content,design:o.design,embedSettings:o.embedSettings,locale:o.locale,managedUserId:o.managedUserId})},t);var o,s;return new pe(n,(e=>ot(e)))}))}createCompositionFromWidget(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.createCompositionFromWidgetRaw(e,t);return yield i.value()}))}createWidgetRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.newWidget)throw new ue("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 pe(n,(e=>rt(e)))}))}createWidget(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.createWidgetRaw(e,t);return yield i.value()}))}deleteWidgetRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 me(n)}))}deleteWidget(e,t){return Hi(this,void 0,void 0,(function*(){yield this.deleteWidgetRaw(e,t)}))}detachWidgetRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 me(n)}))}detachWidget(e,t){return Hi(this,void 0,void 0,(function*(){yield this.detachWidgetRaw(e,t)}))}duplicateWidgetRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling duplicateWidget().');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("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 pe(n,(e=>ft(e)))}))}duplicateWidget(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.duplicateWidgetRaw(e,t);return yield i.value()}))}getWidgetContentSchemaRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 pe(n)}))}getWidgetContentSchema(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.getWidgetContentSchemaRaw(e,t);return yield i.value()}))}getWidgetDesignSchemaRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 pe(n)}))}getWidgetDesignSchema(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.getWidgetDesignSchemaRaw(e,t);return yield i.value()}))}getWidgetPublishHistoryRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.widgetId)throw new ue("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 pe(n,(e=>$t(e)))}))}getWidgetPublishHistory(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.getWidgetPublishHistoryRaw(e,t);return yield i.value()}))}getWidgetsBatchRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.getWidgetsBatchRequest)throw new ue("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 pe(n,(e=>Ft(e)))}))}getWidgetsBatch(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.getWidgetsBatchRaw(e,t);return yield i.value()}))}getWidgetsRaw(e,t){return Hi(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 pe(o,(e=>Nt(e)))}))}getWidgets(){return Hi(this,arguments,void 0,(function*(e={},t){const i=yield this.getWidgetsRaw(e,t);return yield i.value()}))}renameWidgetPublishHistoryTitleRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.widgetId)throw new ue("widgetId",'Required parameter "widgetId" was null or undefined when calling renameWidgetPublishHistoryTitle().');if(null==e.version)throw new ue("version",'Required parameter "version" was null or undefined when calling renameWidgetPublishHistoryTitle().');if(null==e.renameWidgetPublishHistoryTitleRequest)throw new ue("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 pe(n,(e=>Zt(e)))}))}renameWidgetPublishHistoryTitle(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.renameWidgetPublishHistoryTitleRaw(e,t);return yield i.value()}))}setWidgetPublishHistoryLiveRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.widgetId)throw new ue("widgetId",'Required parameter "widgetId" was null or undefined when calling setWidgetPublishHistoryLive().');if(null==e.version)throw new ue("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 pe(n,(e=>si(e)))}))}setWidgetPublishHistoryLive(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.setWidgetPublishHistoryLiveRaw(e,t);return yield i.value()}))}updateWidgetRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling updateWidget().');if(null==e.updateWidgetRequest)throw new ue("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 me(n)}))}updateWidget(e,t){return Hi(this,void 0,void 0,(function*(){yield this.updateWidgetRaw(e,t)}))}updateWidgetRepositoryRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling updateWidgetRepository().');if(null==e.updateWidgetRepositoryRequest)throw new ue("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 pe(n,(e=>wi(e)))}))}updateWidgetRepository(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.updateWidgetRepositoryRaw(e,t);return yield i.value()}))}uploadWidgetThumbnailRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling uploadWidgetThumbnail().');if(null==e.uploadWidgetThumbnailRequest)throw new ue("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 pe(n,(e=>Ii(e)))}))}uploadWidgetThumbnail(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.uploadWidgetThumbnailRaw(e,t);return yield i.value()}))}}class Gi extends Error{constructor(e,t,i){super(e),this.code=t,this.statusCode=i,this.name="AuthError"}}class Xi{constructor(e={}){var t,i;this.currentToken=null,this.apiKey=null,this.refreshTimer=null,this.config=Object.assign({apiUrl:e.apiUrl||z(),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 re({basePath:this.config.apiUrl,apiKey:()=>t(this,void 0,void 0,(function*(){return e})),headers:{"X-SDK-Version":`embed-sdk/${_}`}});return new Ki(i)}createTokensApiForAccessToken(e){const i=new re({basePath:this.config.apiUrl,accessToken:()=>t(this,void 0,void 0,(function*(){return e})),headers:{"X-SDK-Version":`embed-sdk/${_}`}});return new Ki(i)}setApiKey(e){this.apiKey=e,this.currentToken={token:e,tokenType:"API-Key",expiresAt:null,scopes:[]},this.config.debug&&te.debug("AuthManager: API key set")}getValidToken(e){return t(this,void 0,void 0,(function*(){if(this.currentToken&&this.isTokenValid(this.currentToken)){if(Xi.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 Gi("No authentication method available","NO_AUTH_METHOD")}))}exchangeApiKeyForJWT(e){return t(this,void 0,void 0,(function*(){var t;if(!this.apiKey)throw new Gi("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 Gi("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&&te.info("AuthManager: Token exchanged successfully",{scopes:r.scopes,expiresAt:r.expiresAt}),r}catch(e){const t=e instanceof Gi?e:new Gi(`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(Xi.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)?(Xi.validatedTokens.add(this.currentToken.token),!0):(this.clearToken(),!1)}catch(e){return this.config.debug&&te.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&&Xi.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&&te.info("AuthManager: Token refreshed automatically")}catch(e){this.config.debug&&te.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&&te.debug("AuthManager: Disposed")}}Xi.validatedTokens=new Set;const Yi=P,Ji={};let Qi=null,Zi=null;const en={API_URL:q.PROD_API_URL,API_VERSION:q.VERSION,CLIENT_URL:q.PROD_CLIENT_URL,PRODUCTION_URL:q.PROD_CDN_URL,NODE_ENV:"production",ENABLE_EDITING:q.ENABLE_EDITING,API_KEY:Ji.PUBLIC_API_KEY,AXIOM_API_KEY:Ji.PUBLIC_AXIOM_API_KEY,STATSIG_KEY:Ji.PUBLIC_STATSIG_KEY};function tn(){return Zi||(Zi=new Xi({apiUrl:sn(),debug:hn.enabled})),Zi}function nn(){return t(this,void 0,void 0,(function*(){if(Zi&&Zi.hasAuthMethod())try{return yield Zi.getValidToken()}catch(e){}if(Qi)return yield Qi.getToken();const e=en.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 on(e){const t=(null==e?void 0:e.tokenProvider)||Qi;if(!t){const t=(null==e?void 0:e.apiKey)||en.API_KEY;return{apiKey:t,basePath:(null==e?void 0:e.basePath)||sn(),tokenProvider:t?new ie(t):void 0}}return{basePath:(null==e?void 0:e.basePath)||sn(),tokenProvider:t}}function sn(){return en.API_URL}function rn(){return en.PRODUCTION_URL}function an(){return`${sn()}${en.API_VERSION}`}const dn={isProduction:"production"===en.NODE_ENV,apiUrl:sn(),apiKey:en.API_KEY},ln={renderMode:j,displayMode:$,resize:B,width:N,height:F,autoscale:K},cn={customElements:H.CUSTOM_ELEMENTS,http3:H.HTTP3,resizeObserver:H.RESIZE_OBSERVER},un={batchSize:V,loadTimeout:G,retryAttempts:X},hn={enabled:L,logLevel:U},gn={AXIOM_API_KEY:en.AXIOM_API_KEY||"",AXIOM_DATASET:n,AXIOM_API_ENDPOINT:i,STATSIG_API_KEY:en.STATSIG_KEY||"",STATSIG_API_ENDPOINT:o,ENABLE_PERFORMANCE_TRACKING:s,PERFORMANCE_SAMPLE_RATE:r,PERFORMANCE_REPORTING_ENDPOINT:d,LCP_THRESHOLD:l,LCP_WARNING_THRESHOLD:c,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},pn={ROOT_MARGIN:k,THRESHOLD:S,MAX_CONCURRENT:C,RETRY_ATTEMPTS:A,RETRY_DELAY:E},mn={MAX_PRELOAD_REQUESTS:R,PREFETCH_TIMEOUT:x,CACHE_DURATION:M,MAX_CONCURRENT_REQUESTS:W,DNS_PREFETCH_ENABLED:D,PRECONNECT_ENABLED:O},fn={DEBUG:L,LOG_LEVEL:U,VERSION:P};var vn=Object.freeze({__proto__:null,BROWSER_FEATURES:cn,DEBUG:hn,DEFAULT_WIDGET_CONFIG:ln,LAZY_LOADING_CONFIG:pn,PERFORMANCE:un,PERFORMANCE_CONFIG:gn,RESOURCE_CONFIG:mn,SDK_CONFIG:fn,VERSION:Yi,config:en,createSdkConfig:on,environment:dn,getApiUrl:sn,getAuthManager:tn,getAuthToken:nn,getCdnUrl:rn,getConfiguration:function(){return on()},getTokenProvider:function(){return Qi},getVersionedApiUrl:an,setApiKey:function(e){tn().setApiKey(e)},setTokenProvider:function(e){Qi=e}});class yn{constructor(){this.foundWidgets=[],this.scanStartTime=0}scan(){this.scanStartTime=performance.now();const e=["[data-composition-id]","[data-widget-id]","widgetic-widget","widgetic"],t=[];for(const i of e){const e=document.querySelectorAll(i);for(const i of Array.from(e))this.isValidWidget(i)&&t.push(i)}this.foundWidgets=t;const i=performance.now()-this.scanStartTime;return te.info(`FastScanner: Found ${t.length} widgets in ${i.toFixed(2)}ms`),t}isValidWidget(e){return e.hasAttribute("data-composition-id")||e.hasAttribute("data-widget-id")||e.hasAttribute("composition-id")}getScanTime(){return this.scanStartTime>0?performance.now()-this.scanStartTime:0}}class wn{constructor(){this.loadedChunks=new Set,this.loadingPromises=new Map,this.loadStartTime=0,this.loadStartTime=performance.now()}loadCoreChunks(){return t(this,void 0,void 0,(function*(){const e=[this.loadChunk("core",(()=>Promise.resolve().then((function(){return vn})))),this.loadChunk("scanner",(()=>Promise.resolve().then((function(){return eo})))),this.loadChunk("scanner",(()=>Promise.resolve().then((function(){return ao}))))];yield Promise.all(e),te.debug("ProgressiveLoader: Core chunks loaded")}))}loadRenderingChunks(){return t(this,void 0,void 0,(function*(){const e=[this.loadChunk("renderers",(()=>Promise.resolve().then((function(){return ir})))),this.loadChunk("renderers",(()=>Promise.resolve().then((function(){return _s})))),this.loadChunk("renderers",(()=>Promise.resolve().then((function(){return Qs}))))];yield Promise.all(e),te.debug("ProgressiveLoader: Rendering chunks loaded")}))}loadApiChunks(){return t(this,void 0,void 0,(function*(){const e=[this.loadChunk("api",(()=>Promise.resolve().then((function(){return go})))),this.loadChunk("api",(()=>Promise.resolve().then((function(){return yo}))))];yield Promise.all(e),te.debug("ProgressiveLoader: API chunks loaded")}))}loadFeatureChunk(e){return t(this,void 0,void 0,(function*(){switch(e){case"messaging":return this.loadChunk("messaging",(()=>Promise.resolve().then((function(){return Fs}))));case"media":return this.loadChunk("media",(()=>Promise.resolve().then((function(){return Ds}))));case"performance":return this.loadChunk("performance",(()=>Promise.resolve().then((function(){return dr}))));case"advanced":return this.loadChunk("advanced",(()=>Promise.resolve().then((function(){return kr}))));case"security":return this.loadChunk("security",(()=>Promise.resolve().then((function(){return Rr}))));case"display":return this.loadChunk("display",(()=>Promise.resolve().then((function(){return Dr}))));case"abTesting":return this.loadChunk("abTesting",(()=>Promise.resolve().then((function(){return ea}))));default:return te.warn(`ProgressiveLoader: Unknown feature '${e}'`),null}}))}loadChunk(e,i){return t(this,void 0,void 0,(function*(){if(this.loadedChunks.has(e))return;if(this.loadingPromises.has(e))return this.loadingPromises.get(e);const t=i().then((t=>(this.loadedChunks.add(e),te.debug(`ProgressiveLoader: Loaded chunk '${e}'`),t))).catch((t=>{throw te.error(`ProgressiveLoader: Failed to load chunk '${e}'`,t),t}));return this.loadingPromises.set(e,t),t}))}getLoadedChunks(){return Array.from(this.loadedChunks)}getTotalLoadTime(){return performance.now()-this.loadStartTime}}class bn{constructor(e={}){this.scanner=new yn,this.loader=new wn,this.config=Object.assign({debug:!1,preloadCritical:!0,scanInterval:0,enableLazyLoading:!0},e),this.initStartTime=performance.now(),this.stats={scanTime:0,widgetsFound:0,chunksLoaded:[],totalLoadTime:0},this.config.debug&&(ee.setDebug(!0),ee.setLevel("debug"))}initialize(){return t(this,void 0,void 0,(function*(){try{te.info("WidgeticBootstrap: Starting fast initialization...");const e=this.scanner.scan();if(this.stats.widgetsFound=e.length,this.stats.scanTime=this.scanner.getScanTime(),0===e.length)return te.info("WidgeticBootstrap: No widgets found, minimal initialization"),this.finalizeStats(),this.stats;this.config.preloadCritical&&(yield this.loader.loadCoreChunks());const t=this.analyzeWidgetRequirements(e);let i=[];try{const{analyzeWidgetRequirementsEnhanced:t}=yield Promise.resolve().then((function(){return na}));i=t(e)}catch(e){}const n=[...new Set([...t,...i])];return yield this.loadRequiredChunks(n),yield this.initializeFullSDK(e),this.finalizeStats(),te.info(`WidgeticBootstrap: Initialization complete in ${this.stats.totalLoadTime.toFixed(2)}ms`),this.stats}catch(e){throw te.error("WidgeticBootstrap: Initialization failed",e),e}}))}analyzeWidgetRequirements(e){const t=new Set;t.add("rendering"),t.add("api");for(const i of e){("widgetic-abtest"===i.tagName.toLowerCase()||i.hasAttribute("experiment-id")||i.hasAttribute("data-ab-test"))&&(t.add("abTesting"),t.add("messaging")),i.hasAttribute("data-interactive")&&t.add("messaging");const e=this.extractWidgetCapabilities(i);e.length>0&&e.forEach((e=>t.add(e)));const n=i.getAttribute("data-widget-id")||"",o=i.getAttribute("data-widget-type")||"";(n.includes("video")||n.includes("audio")||n.includes("media")||"media"===o)&&t.add("media"),(i.hasAttribute("data-editing")||"editing"===i.getAttribute("data-render-mode"))&&t.add("advanced");const s=i.getAttribute("data-display-mode");"overlay"!==s&&"popup"!==s&&"fullscreen"!==s||t.add("display"),(n.includes("form")||n.includes("input")||n.includes("contact")||"form"===o)&&t.add("security"),"gallery"!==o&&"interactive"!==o||t.add("messaging")}return te.debug("WidgeticBootstrap: Required features:",Array.from(t)),Array.from(t)}extractWidgetCapabilities(e){var t;const i=[];try{const n=e.getAttribute("data-widget-meta");if(n){const e=JSON.parse(n);(e.mediaCapabilities||e.supportsMedia)&&i.push("media"),(e.textCapabilities||e.supportsText||e.hasTextFields)&&i.push("security"),(e.supportsInteraction||e.hasInteractiveElements)&&i.push("messaging"),(e.supportsFullscreen||e.supportsOverlay)&&i.push("display"),(e.supportsABTesting||e.trackingCapabilities)&&i.push("abTesting")}const o=e.getAttribute("data-widget-type");if(o)switch(o){case"media":i.push("media");break;case"form":i.push("security","messaging");break;case"gallery":case"interactive":i.push("messaging")}if(e.matches("widgetic-widget[data-capabilities]")){const n=(null===(t=e.getAttribute("data-capabilities"))||void 0===t?void 0:t.split(","))||[];i.push(...n.map((e=>e.trim())))}}catch(e){te.debug("Failed to parse widget metadata, using fallback detection",{error:e})}return i}loadRequiredChunks(e){return t(this,void 0,void 0,(function*(){const t=[];for(const i of e)switch(i){case"rendering":t.push(this.loader.loadRenderingChunks());break;case"api":t.push(this.loader.loadApiChunks());break;default:t.push(this.loader.loadFeatureChunk(i))}yield Promise.all(t)}))}initializeFullSDK(e){return t(this,void 0,void 0,(function*(){var t;const{getSDK:i}=yield Promise.resolve().then((function(){return Ja})),n=i({debug:this.config.debug,lazyLoading:{enabled:null===(t=this.config.enableLazyLoading)||void 0===t||t,config:{}}});yield n.init(),te.info(`WidgeticBootstrap: Processing ${e.length} widgets through full SDK`)}))}finalizeStats(){this.stats.totalLoadTime=performance.now()-this.initStartTime,this.stats.chunksLoaded=this.loader.getLoadedChunks()}getStats(){return Object.assign({},this.stats)}}let In=null;function Tn(e){return t(this,void 0,void 0,(function*(){return In?(te.warn("WidgeticBootstrap: Already initialized"),In.getStats()):(In=new bn(e),yield In.initialize())}))}function kn(){return(null==In?void 0:In.getStats())||null}if("undefined"!=typeof document){const e=()=>{window.__WIDGETIC_SDK_INITIALIZED__||Tn({debug:"development"===en.NODE_ENV,preloadCritical:!0}).catch((e=>{te.error("WidgeticBootstrap: Auto-initialization failed",e)}))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}"undefined"!=typeof window&&(window.WidgeticBootstrap={init:Tn,getStats:kn,version:"1.0.0"});const Sn=2147483647;function Cn(e){const t=e.getAttribute("composition-id");if(!t)throw new Error("Missing required composition-id attribute");return{compositionId:t,renderMode:An(e.getAttribute("render-mode")),displayMode:En(e.getAttribute("display-mode")),resize:Rn(e.getAttribute("resize")),width:parseInt(e.getAttribute("width")||"")||ln.width,height:parseInt(e.getAttribute("height")||"")||ln.height,autoscale:Nn(e),adaptive:xn(e.getAttribute("adaptive")),responsive:Mn(e.getAttribute("responsive")),device:Zn(e),fullscreen:Wn(e),triggers:Xn(e),overlay:On(e),popup:$n(e),media:Vn(e),content:Gn(e)}}function An(e){switch(e){case"iframe":case"custom-element":return e;default:return"auto"}}function En(e){switch(e){case"overlay":case"popup":case"fullscreen":case"modal":return e;default:return"inline"}}function Rn(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 xn(e){if(!e)return;const t=parseInt(e);return isNaN(t)?void 0:t}function Mn(e){if(!e)return;const t=parseInt(e);return isNaN(t)?void 0:t}function Wn(e){if("enabled"===e.getAttribute("fullscreen")||"true"===e.getAttribute("fullscreen-enabled"))return{enabled:!0,trigger:Dn(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 Dn(e){switch(e){case"click":case"double-click":case"hover":case"auto":case"manual":return e;default:return"click"}}function On(e){if("enabled"===e.getAttribute("overlay")||"true"===e.getAttribute("overlay-enabled"))return{enabled:!0,position:qn(e.getAttribute("overlay-position")),backdrop:Un(e),background:Pn(e,Un(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:_n(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:zn(e.getAttribute("overlay-animation")),overlayWidth:e.getAttribute("overlay-width")||void 0,overlayHeight:e.getAttribute("overlay-height")||void 0,overlayResize:jn(e.getAttribute("overlay-resize-mode")),keepDimensions:"false"!==e.getAttribute("keep-dimensions"),embedTarget:e.getAttribute("embed-target")||void 0}}function Ln(e){return"true"===e.getAttribute("overlay-backdrop")}function Un(e){return"false"!==e.getAttribute("overlay-backdrop")}function Pn(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 _n(e){switch(e){case"click":case"hover":case"manual":case"auto":return e;default:return"click"}}function zn(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 qn(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 jn(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 $n(e){if("enabled"===e.getAttribute("popup")||"true"===e.getAttribute("popup-enabled"))return{enabled:!0,trigger:Bn(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 Bn(e){switch(e){case"click":case"manual":return e;default:return"click"}}function Nn(e){const t=e.getAttribute("autoscale");return!!t&&(("true"===t||""===t||"false"!==t)&&(Fn(e)||!0))}function Fn(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 Kn(e){return`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function Hn(e){return"widgetic"===e.tagName.toLowerCase()&&e.hasAttribute("composition-id")}function Vn(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 l=e.getAttribute("media-global-volume")||e.getAttribute("data-media-global-volume");return null!==l&&(t.globalVolume="true"===l||""===l),t}function Gn(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 Xn(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:Jn(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:Yn(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:jn(e.getAttribute("overlay-resize-mode")),backdrop:Ln(e),background:Pn(e,Ln(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 Yn(e){const t=parseInt(e.getAttribute("overlay-z-index")||"");if(Number.isFinite(t)&&!(t<=0))return Math.min(t,Sn)}function Jn(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 Zn(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}}var eo=Object.freeze({__proto__:null,generateInstanceId:Kn,isValidWidgetElement:Hn,parseTriggerConfig:Xn,parseWidgetConfig:Cn});function to(){return"undefined"==typeof window?{customElements:!1,http3:!1,resizeObserver:!1,fullscreenApi:!1,popupBlocking:!1}:{customElements:"undefined"!=typeof customElements&&"function"==typeof customElements.define,http3:io(),resizeObserver:"undefined"!=typeof ResizeObserver,fullscreenApi:no(),popupBlocking:oo()}}function io(){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 no(){return!("undefined"==typeof document||!document.documentElement)&&!!(document.documentElement.requestFullscreen||document.documentElement.webkitRequestFullscreen||document.documentElement.mozRequestFullScreen||document.documentElement.msRequestFullscreen)}function oo(){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 so(e,t){switch(e){case"custom-element":case"auto":default:return t.customElements?"custom-element":"iframe";case"iframe":return"iframe"}}function ro(){if("undefined"==typeof localStorage)return!1;try{const e="widgetic-test";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}}var ao=Object.freeze({__proto__:null,checkSdkInitialization:function(){if("undefined"==typeof window)return!1;const e="widgetic-sdk-initialized";return ro()?!!localStorage.getItem(e)||(localStorage.setItem(e,Date.now().toString()),!1):!!window.__widgeticInitialized},clearSdkInitialization:function(){ro()&&localStorage.removeItem("widgetic-sdk-initialized"),delete window.__widgeticInitialized},detectBrowserCapabilities:to,determineBestRenderMode:so,hasIntersectionObserver:function(){return"undefined"!=typeof IntersectionObserver},isLocalStorageAvailable:ro});const lo={maxBatchSize:50,debounceDelay:10,retryAttempts:3,retryBaseDelay:1e3,cacheTTL:3e5};class co{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({},lo),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 nn(),o=new re({basePath:an(),apiKey:()=>t(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${Yi}`}}),s=new Ni(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 nn(),o=new re({basePath:an(),apiKey:()=>t(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${Yi}`}}),s=new Vi(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 uo=null;function ho(){return uo||(uo=new co),uo}var go=Object.freeze({__proto__:null,BatchApiClient:co,getBatchClient:ho,resetBatchClient:function(){uo=null}});const po={cacheTTL:18e5,loadTimeout:1e4,maxRetries:3,retryDelay:1e3,enableHttp3:!0,cdnBaseUrl:rn()};class mo{constructor(e={}){this.moduleCache=new Map,this.loadingPromises=new Map,this.dependencyGraph=new Map,this.http3Supported=null,this.config=Object.assign(Object.assign({},po),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 fo=null;function vo(){return fo||(fo=new mo),fo}var yo=Object.freeze({__proto__:null,ModuleLoader:mo,getModuleLoader:vo,resetModuleLoader:function(){fo=null}});const wo=["DOMAIN_NOT_ALLOWED","UNPUBLISHED","SUSPENDED","NOT_FOUND","RATE_LIMITED"],bo={DOMAIN_NOT_ALLOWED:"domain_not_allowed",UNPUBLISHED:"unpublished",SUSPENDED:"suspended",NOT_FOUND:"not_found",RATE_LIMITED:"rate_limited"};function Io(e){return wo.includes(e)?bo[e]:null}const To=/^https:\/\/[^\s"'<>]+\.(?:png|jpe?g|webp|gif|avif)(?:\?[^\s"'<>]*)?$/i,ko=new Set;function So(e,t,i=e=>e){if("undefined"!=typeof document&&document.head)try{for(const n of function(e,t,i=2){const n=[];let o=0;const s=(e,t)=>{if(n.length>=i||o>=400)return;if(o+=1,"string"==typeof e)return void(To.test(e)&&!n.includes(e)&&n.push(e));if(t>=4||null===e||"object"!=typeof e)return;const r=Array.isArray(e)?e:Object.values(e);for(const e of r)s(e,t+1)};return s(e,0),s(t,0),n}(e,t)){const e=i(n);if(ko.has(e))continue;ko.add(e);const t=document.createElement("link");t.setAttribute("rel","preload"),t.setAttribute("as","image"),t.setAttribute("href",e),document.head.appendChild(t)}}catch(e){}}const Co=[480,960,1600],Ao=["static.widgetic.com","cdn.widgetic.com"],Eo=/^https:\/\/[^\s"'<>]+\.(?:png|jpe?g|webp|avif)(?:\?[^\s"'<>]*)?$/i;function Ro(){var e;if("undefined"==typeof window)return Co[Co.length-1];return function(e){var t;const i=Co,n=Number.isFinite(e)&&e>0?e:i[i.length-1];return null!==(t=i.find((e=>e>=n)))&&void 0!==t?t:i[i.length-1]}((window.innerWidth||(null===(e=document.documentElement)||void 0===e?void 0:e.clientWidth)||0)*Math.min(window.devicePixelRatio||1,2))}function xo(e,t){let i=0;const n=(e,o)=>{if(i+=1,i>5e3)return e;if("string"==typeof e)return function(e,t){if(!Eo.test(e))return e;let i;try{i=new URL(e)}catch(t){return e}if(!Ao.includes(i.hostname.toLowerCase()))return e;if(i.pathname.startsWith("/cdn-cgi/"))return e;const n=`width=${t},fit=scale-down,quality=80,format=auto`;return`${i.origin}/cdn-cgi/image/${n}/${e}`}(e,t);if(o>=8||null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map((e=>n(e,o+1)));const s={};for(const[t,i]of Object.entries(e))s[t]=n(i,o+1);return s};return n(e,0)}function Mo(e,t,i){try{if(!function(e){if(!e||!0!==e.optimize)return!1;if("undefined"==typeof window||"undefined"==typeof document)return!1;if(!1===window.WIDGETIC_IMAGE_OPTIMIZE)return!1;const t=document.querySelectorAll("script[src*='embed-sdk'][data-image-optimize]");for(const e of Array.from(t))if("off"===(e.getAttribute("data-image-optimize")||"").trim().toLowerCase())return!1;return!0}(e))return{content:t,contentItems:i};const n=Ro();return{content:xo(t,n),contentItems:xo(i,n)}}catch(e){return{content:t,contentItems:i}}}const Wo="lookups",Do=864e5;function Oo(){if("undefined"==typeof window||"undefined"==typeof document)return!1;const e=window;if(!e.indexedDB)return!1;if(!1===e.WIDGETIC_EMBED_LOOKUP_CACHE)return!1;const t=document.querySelectorAll("script[src*='embed-sdk'][data-lookup-cache]");for(const e of Array.from(t))if("off"===(e.getAttribute("data-lookup-cache")||"").trim().toLowerCase())return!1;return!0}let Lo=null;function Uo(){return Lo||(Lo=new Promise((e=>{try{const i=window.indexedDB.open("widgetic-embed-lookup",1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Wo)||i.result.createObjectStore(Wo)},i.onsuccess=()=>{e(i.result),function(e){t(this,void 0,void 0,(function*(){try{const t=e.transaction(Wo,"readwrite"),i=t.objectStore(Wo).openCursor(),n=Date.now()-Do;i.onsuccess=()=>{const e=i.result;if(!e)return;const t=e.value;(!t||"number"!=typeof t.storedAtMs||t.storedAtMs<n)&&e.delete(),e.continue()}}catch(e){}}))}(i.result)},i.onerror=()=>e(null),i.onblocked=()=>e(null)}catch(t){e(null)}})),Lo)}const Po="https://cdn.widgetic.com",_o="DOMAIN_NOT_ALLOWED";function zo(){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 qo(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 jo(e,t){if(!e||"object"!=typeof e)return null;let i="string"==typeof e.embedUrl?e.embedUrl:"";if(!i&&"string"==typeof e.js_path&&e.js_path.trim()){const t=e.js_path.trim();i=/^https?:\/\//i.test(t)?t:`${Po}${t.startsWith("/")?"":"/"}${t}`}else!i&&"string"==typeof e.embed_url&&e.embed_url.trim()&&(i=e.embed_url.trim());if(!i)return null;const n=function(e){if(!e||"object"!=typeof e)return;const t=e;return"string"!=typeof t.moduleUrl||"number"!=typeof t.contractVersion?void 0:{moduleUrl:t.moduleUrl,contractVersion:t.contractVersion,moduleHash:"string"==typeof t.moduleHash?t.moduleHash:null}}(e.direct),o="string"==typeof e.compositionId?e.compositionId:void 0,s="string"==typeof e.widgetId?e.widgetId:"string"==typeof e.id?e.id:void 0,r="string"==typeof e.entryWriteToken?e.entryWriteToken:void 0;let a;if(e.entries&&"object"==typeof e.entries){const t=e.entries;"string"==typeof t.url&&(a=Object.assign({url:t.url},"string"==typeof t.writeToken?{writeToken:t.writeToken}:r?{writeToken:r}:{}))}else r&&o&&t&&(a={url:`${t.replace(/\/+$/,"")}/embed/compositions/${o}/entries`,writeToken:r});const d=e.media,l=d&&"object"==typeof d&&"boolean"==typeof d.optimize?{optimize:d.optimize}:void 0,c=Mo(l,e.content&&"object"==typeof e.content?e.content:{},Array.isArray(e.contentItems)?e.contentItems:[]);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({embedUrl:i,compositionId:o},s?{widgetId:s}:{}),{design:e.design&&"object"==typeof e.design?e.design:{},content:c.content,contentItems:c.contentItems}),l?{media:l}:{}),n?{direct:n}:{}),r?{entryWriteToken:r}:{}),a?{entries:a}:{})}function $o(e){return t(this,void 0,void 0,(function*(){let t=null;try{t=yield e.json()}catch(e){t=null}const i=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;const t=e.code;return"string"==typeof t&&t.length>0&&t.length<=64?t:null}(t),n=(i&&Io(i)?i:null)||(429===(o=e.status)?"RATE_LIMITED":404===o?"NOT_FOUND":null);var o;if(!n)return null;const s=Io(n);return s?{gatewayCode:n,stateCode:s}:null}))}const Bo=new Map;function No(e){try{return new URL(e).origin}catch(e){return""}}function Fo(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!==_o)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:_o,reason:n}}catch(e){return null}}))}(i);if(e)return{kind:"refused",refusal:e};const n=yield $o(i);return n?{kind:"failed",failure:n}:{kind:"unavailable"}}return{kind:"json",json:yield i.json()}}catch(e){return{kind:"unavailable"}}}))}function Ko(e){const i=Bo.get(e);if(i)return i;const n=Fo(e).then((i=>("json"===i.kind&&jo(i.json,No(e))&&function(e,i){t(this,void 0,void 0,(function*(){if(!Oo())return;const t=yield Uo();if(t)try{const n={json:i,storedAtMs:Date.now()};t.transaction(Wo,"readwrite").objectStore(Wo).put(n,e)}catch(e){}}))}(e,i.json),i)));return Bo.set(e,n),n.finally((()=>{Bo.get(e)===n&&Bo.delete(e)})),n}function Ho(e){return JSON.parse(JSON.stringify(e))}function Vo(e){return t(this,void 0,void 0,(function*(){const i=No(e),n=yield function(e){return t(this,void 0,void 0,(function*(){if(!Oo())return null;const t=yield Uo();return t?new Promise((i=>{try{const n=t.transaction(Wo,"readonly").objectStore(Wo).get(e);n.onsuccess=()=>{const e=n.result,t=e&&"number"==typeof e.storedAtMs&&e.json&&"object"==typeof e.json;i(t?e:null)},n.onerror=()=>i(null)}catch(e){i(null)}})):null}))}(e);if(n&&function(e,t=Date.now()){const i=t-e.storedAtMs;return i>=0&&i<=3e4}(n)){const t=jo(Ho(n.json),i);if(t)return Ko(e),So(t.content,t.contentItems),{kind:"payload",payload:t,gatewayOrigin:i}}const o=yield Ko(e);if("json"!==o.kind)return o;const s=jo(Ho(o.json),i);return s?(So(s.content,s.contentItems),{kind:"payload",payload:s,gatewayOrigin:i}):{kind:"unavailable"}}))}function Go(e){return"refused"===e.kind?{status:"refused",refusal:e.refusal}:"failed"===e.kind?{status:"failed",failure:e.failure}:{status:"found",payload:e.payload,gatewayOrigin:e.gatewayOrigin||void 0}}function Xo(e){const t=`/embed/compositions/${e}`,i=[];for(const e of zo())i.push(`${e}${t}`);const n=sn().replace(/\/+$/,"");i.push(`${n}${t}`);const o=String(q.PROD_API_URL).replace(/\/+$/,"");return o&&i.push(`${o}${t}`),[...new Set(i)]}function Yo(e){return t(this,void 0,void 0,(function*(){const t=zo();for(const i of t){const t=yield Vo(`${i}/embed/compositions/${e}`);if("unavailable"!==t.kind)return Go(t)}const i=yield function(e){const t=qo(e);return t?Promise.resolve(t):"undefined"==typeof document?Promise.resolve(null):new Promise((t=>{const i=document.createElement("script");i.src=`${Po}/embed/compositions/${e}.js`,i.async=!0,i.onload=()=>t(qo(e)),i.onerror=()=>t(null),document.head.appendChild(i)}))}(e);if(i){for(const t of Xo(e)){const e=yield Vo(t);if("refused"===e.kind)return Go(e);if("failed"!==e.kind&&"payload"===e.kind){const t=e.payload;return{status:"found",payload:Object.assign(Object.assign({},t),{embedUrl:t.embedUrl||i}),gatewayOrigin:e.gatewayOrigin||void 0}}}return{status:"found",payload:{embedUrl:i,compositionId:e}}}let n=null;for(const t of Xo(e)){const e=yield Vo(t);if("refused"===e.kind)return Go(e);if("failed"!==e.kind){if("payload"===e.kind)return Go(e)}else n=e.failure}return n?{status:"failed",failure:n}:{status:"not-found"}}))}function Jo(e){return t(this,void 0,void 0,(function*(){const t=zo();for(const i of t){const t=yield Vo(`${i}/widgets/${encodeURIComponent(e)}`);if("unavailable"!==t.kind)return Go(t)}const i=qo(e);let n=null;for(const t of function(e){const t=`/widgets/${encodeURIComponent(e)}`,i=[];for(const e of zo())i.push(`${e}${t}`);const n=sn().replace(/\/+$/,"");i.push(`${n}${t}`);const o=String(q.PROD_API_URL).replace(/\/+$/,"");return o&&i.push(`${o}${t}`),[...new Set(i)]}(e)){const e=yield Vo(t);if("refused"===e.kind)return Go(e);if("failed"!==e.kind){if("payload"===e.kind)return Go(e)}else n=e.failure}return i?{status:"found",payload:{embedUrl:i,widgetId:e}}:n?{status:"failed",failure:n}:{status:"not-found"}}))}const Qo=new Set;function Zo(e,t){var i;if(Qo.has(e))return;Qo.add(e);"undefined"!=typeof window&&(null===(i=window.location)||void 0===i?void 0:i.hostname)&&window.location.hostname,t.reason&&t.reason}function es(e,t,i,n,o){const s=document.createElement("iframe");return s.src=e,s.width=t,s.height=i,s.setAttribute("frameborder","0"),s.setAttribute("allowfullscreen",""),s.style.border="0",s.style.display="block",s.style.maxWidth="100%",n&&s.setAttribute("data-composition-id",n),function(e,t){if(!t)return;const i=t.design&&Object.keys(t.design).length>0?t.design:null,n=t.content&&Object.keys(t.content).length>0?t.content:null,o=t.contentItems&&t.contentItems.length>0?t.contentItems:null;if(!i&&!n&&!o)return;const s=()=>{const t=e.contentWindow;if(!t)return;const s={type:"widgetic:update"};i&&(s.design=i),n&&(s.content=n),o&&(s.contentItems=o),t.postMessage(s,"*")};window.addEventListener("message",(t=>{t.source===e.contentWindow&&"widgetic:ready"===(t.data&&t.data.type||"")&&s()})),e.addEventListener("load",(()=>{s(),window.setTimeout(s,80),window.setTimeout(s,400)}))}(s,o),s}const ts=new Set(["id","class","style","title","lang","dir","hidden","tabindex","role","slot","part","draggable","contenteditable","spellcheck","translate","composition-id","compositionid","composition","widget","widget-id","widgetid","src","width","height","resize","resize-mode","render-mode","display-mode","autoscale","adaptive","responsive","theme","mode","colors","context","values","media-resolver","mediaresolver","sandbox","autoload","use-iframe","embed-target","event-trigger","trigger-delay","trigger-scroll-distance","overlay-position","overlay-full-width","overlay-backdrop","max-views","time-period","device-mobile-enabled","device-desktop-enabled","display-on-mobile","display-on-desktop","use-breakpoints","mobile-breakpoint","tablet-breakpoint","desktop-breakpoint","design","content","items","content-items","contentitems"]),is={backgroundcolor:"backgroundColor",textcolor:"textColor",primarycolor:"primaryColor",secondarycolor:"secondaryColor",accentcolor:"accentColor",bordercolor:"borderColor",borderradius:"borderRadius",borderwidth:"borderWidth",fontsize:"fontSize",fontfamily:"fontFamily",fontweight:"fontWeight",lineheight:"lineHeight",letterspacing:"letterSpacing"},ns=new WeakMap;function os(e){const t=e.trim().replace(/^data-/,"").replace(/-([a-zA-Z0-9])/g,((e,t)=>t.toUpperCase())),i=t.toLowerCase();return t===i&&is[i]?is[i]:t}function ss(e){var t,i,n,o,s,r,a,d;const l=(null===(t=e.getAttribute("composition-id"))||void 0===t?void 0:t.trim())||(null===(i=e.getAttribute("compositionid"))||void 0===i?void 0:i.trim())||(null===(n=e.getAttribute("data-composition-id"))||void 0===n?void 0:n.trim())||(null===(o=e.getAttribute("composition"))||void 0===o?void 0:o.trim());if(l)return{kind:"composition",id:l};const c=(null===(s=e.getAttribute("widget"))||void 0===s?void 0:s.trim())||(null===(r=e.getAttribute("widget-id"))||void 0===r?void 0:r.trim())||(null===(a=e.getAttribute("widgetid"))||void 0===a?void 0:a.trim())||(null===(d=e.getAttribute("data-widget-id"))||void 0===d?void 0:d.trim());return c?{kind:"widget",id:c}:null}const rs=new WeakSet;function as(e){if(!e||rs.has(e))return;rs.add(e);const t=[{prop:"values",attr:"values"},{prop:"context",attr:"context"},{prop:"design",attr:"design"},{prop:"content",attr:"content"},{prop:"contentItems",attr:"content-items"}];for(const{prop:i,attr:n}of t){const t=Object.prototype.hasOwnProperty.call(e,i),o=t?e[i]:void 0;t&&delete e[i];const s=t=>{if(null==t||""===t)e.removeAttribute(n);else if("string"==typeof t)e.getAttribute(n)!==t&&e.setAttribute(n,t);else if("object"==typeof t)try{const i=JSON.stringify(t);e.getAttribute(n)!==i&&e.setAttribute(n,i)}catch(e){}};try{Object.defineProperty(e,i,{configurable:!0,enumerable:!1,get:()=>e.getAttribute(n),set(e){s(e)}}),t&&void 0!==o&&s(o)}catch(e){}}const i=[{prop:"mediaResolver",attr:"media-resolver"},{prop:"compositionId",attr:"composition-id"},{prop:"widgetId",attr:"widget-id"}];for(const{prop:t,attr:n}of i){const i=Object.prototype.hasOwnProperty.call(e,t),o=i?e[t]:void 0;i&&delete e[t];const s=t=>{if(null==t||""===t)e.removeAttribute(n);else{const i=String(t);e.getAttribute(n)!==i&&e.setAttribute(n,i)}};try{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get:()=>e.getAttribute(n),set(e){s(e)}}),i&&void 0!==o&&s(o)}catch(e){}}}function ds(e){const t=ss(e);return t?t.id:null}function ls(e){if("SCRIPT"!==e.tagName.toUpperCase())return!1;const t=(e.getAttribute("type")||"").trim().toLowerCase();return"application/json"===t||"application/ld+json"===t||"application/widgetic+json"===t||(e.hasAttribute("data-widgetic-json")||e.hasAttribute("data-widgetic-config"))}function cs(e){const t=e.tagName.toUpperCase();return"SCRIPT"===t?!ls(e):"IFRAME"===t||"STYLE"===t||"TEMPLATE"===t||!!(e.hasAttribute("data-widgetic-direct")||e.hasAttribute("data-widgetic-internal")||e.classList.contains("widgetic-direct-target"))}function us(e){const t=e.toLowerCase();return!!ts.has(t)||(!!t.startsWith("data-widgetic-")||(!!t.startsWith("aria-")||!!t.startsWith("on")))}function hs(e){const t=e.trim();if("true"===t)return!0;if("false"===t)return!1;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch(t){return e}return e}function gs(e){if(!e||!e.trim())return null;try{const t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch(e){}return null}function ps(e){return e.filter((e=>Boolean(e&&"object"==typeof e&&!Array.isArray(e)))).map(((e,t)=>function(e,t){const i={};for(const[t,n]of Object.entries(e))"properties"===t||"inputController"===t||t in Object.prototype||(i[t]=n);if(Array.isArray(e.properties))for(const t of e.properties){if(!t||"object"!=typeof t||Array.isArray(t))continue;const e=t,n="string"==typeof e.name?e.name.trim():"";if(!n||n in Object.prototype)continue;const o=void 0!==e.value&&null!==e.value?e.value:e.defaultValue;void 0!==o&&(i[n]=o)}const n="string"==typeof i.id&&i.id.trim()?i.id:"string"==typeof e.id&&e.id.trim()?e.id:`item-${t+1}`;return Object.assign(Object.assign({id:n,order:t+1},i),{metadata:Object.assign({service:"declarative"},i)})}(e,t)))}function ms(e){if(!e||!e.trim())return null;try{const t=JSON.parse(e);if(Array.isArray(t))return ps(t)}catch(e){}return null}function fs(e,t,i=!1){if(Array.isArray(e)){let n=!1;for(const o of e){if(!o||"object"!=typeof o||Array.isArray(o))continue;const e=o,s="string"==typeof e.name?e.name.trim():"";if(!s||s in Object.prototype)continue;const r=void 0!==e.value&&null!==e.value?e.value:e.defaultValue;null!=r&&(t[s]=i?"string"==typeof r?r:String(r):r,n=!0)}return n}if(e&&"object"==typeof e&&!Array.isArray(e)){let n=!1;for(const[o,s]of Object.entries(e))if(o&&!(o in Object.prototype)&&s&&"object"==typeof s&&!Array.isArray(s)){const e=s;if("defaultValue"in e||"value"in e||"inputController"in e){const s=void 0!==e.value&&null!==e.value?e.value:e.defaultValue;null!=s&&(t[o]=i?"string"==typeof s?s:String(s):s,n=!0);continue}}return n}return!1}function vs(e,t){const i={};let n=!1;if(Array.isArray(e.componentGroups)){n=!0;for(const t of e.componentGroups){if(!t||"object"!=typeof t)continue;const e=t.components;if(Array.isArray(e))for(const t of e){if(!t||"object"!=typeof t)continue;const e=t;if(Array.isArray(e.propertyGroups))for(const t of e.propertyGroups)t&&"object"==typeof t&&fs(t.properties,i,!0);e.properties&&fs(e.properties,i,!0)}}}if(Array.isArray(e.propertyGroups)){n=!0;for(const t of e.propertyGroups)t&&"object"==typeof t&&fs(t.properties,i,!0)}if(e.properties&&fs(e.properties,i,!0)&&(n=!0),n)for(const[e,n]of Object.entries(i))t[e]=String(n);else for(const[i,n]of Object.entries(e))i in Object.prototype||null==n||(t[i]="string"==typeof n?n:JSON.stringify(n))}const ys=new Set(["$schema","id","name","version","contentType","genericContent","contentItems","contentItemsSnapshot","items","options","componentGroups","propertyGroups"]);function ws(e,t){let i=null,n=!1;if(e.genericContent&&"object"==typeof e.genericContent&&!Array.isArray(e.genericContent)){n=!0;const i=e.genericContent;if(!fs(i.properties,t,!1))for(const[e,n]of Object.entries(i))"properties"===e||"inputController"===e||e in Object.prototype||void 0===n||(t[e]=n)}e.properties&&fs(e.properties,t,!1)&&(n=!0);const o=Array.isArray(e.contentItems)?e.contentItems:Array.isArray(e.items)?e.items:Array.isArray(e.contentItemsSnapshot)?e.contentItemsSnapshot:null;o&&(i=ps(o));for(const[i,s]of Object.entries(e))i in Object.prototype||void 0===s||"contentItems"!==i&&"items"!==i&&"contentItemsSnapshot"!==i&&"genericContent"!==i&&"design"!==i&&"content"!==i&&"values"!==i&&(n&&(ys.has(i)||"properties"===i)||(!o||"options"!==i&&"contentType"!==i&&"$schema"!==i)&&(t[i]=s));return i}function bs(e){var t;const i=Array.from(e.children).filter((e=>!cs(e)&&!ls(e)));if(0===i.length)return e.querySelector("[data-widgetic-direct], iframe")||Array.from(e.children).some(ls)?(ns.delete(e),[]):null!==(t=ns.get(e))&&void 0!==t?t:[];const n=i.map(((e,t)=>{var i;e.hasAttribute("data-widgetic-item")||(e.setAttribute("data-widgetic-item","1"),e instanceof HTMLElement&&(e.hidden=!0,e.style.display="none"));const n={};for(const t of Array.from(e.attributes)){const e=t.name.toLowerCase();if("data-widgetic-item"===e||"hidden"===e)continue;if("style"===e&&"display:none;"===t.value.replace(/\s+/g,""))continue;const i=os(t.name);i&&!(i in Object.prototype)&&(n[i]=hs(t.value))}if(0===e.children.length){const t=null===(i=e.textContent)||void 0===i?void 0:i.trim();t&&(void 0===n.content&&(n.content=t),void 0===n.text&&(n.text=t))}const o="string"==typeof n.id&&n.id.trim()?n.id:`item-${t+1}`;return Object.assign(Object.assign({id:o,order:t+1},n),{metadata:Object.assign({service:"declarative"},n)})}));return ns.set(e,n),n}function Is(e,t){if(!e)return null;if(t in e)return t;const i=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===i)return t;return null}function Ts(e,t){const i=function(e,t){var i;const n={},o={};let s=[];const r=Array.from(e.children).filter(ls);for(const e of r){const r=null===(i=e.textContent)||void 0===i?void 0:i.trim();if(!r)continue;let a;try{a=JSON.parse(r)}catch(e){continue}if(Array.isArray(a)){s=ps(a);continue}if(!a||"object"!=typeof a)continue;const d=a,l=(e.getAttribute("data-schema")||e.getAttribute("data-widgetic-json")||e.getAttribute("data-widgetic-config")||"").trim().toLowerCase();if("design"===l){vs(d,n);continue}if("content"===l){const e=ws(d,o);e&&e.length>0&&(s=e);continue}let c=!1;if(d.design&&"object"==typeof d.design&&!Array.isArray(d.design)&&(vs(d.design,n),c=!0),(Array.isArray(d.componentGroups)||Array.isArray(d.propertyGroups))&&(vs(d,n),c=!0),d.content&&"object"==typeof d.content&&!Array.isArray(d.content)){const e=ws(d.content,o);e&&e.length>0&&(s=e),c=!0}if(d.values&&"object"==typeof d.values&&!Array.isArray(d.values)){const e=ws(d.values,o);e&&e.length>0&&(s=e),c=!0}if(d.genericContent||Array.isArray(d.contentItems)||Array.isArray(d.items)||Array.isArray(d.contentItemsSnapshot)){const e=ws(d,o);e&&e.length>0&&(s=e),c=!0}if(!c)for(const[e,i]of Object.entries(d)){if(e in Object.prototype||null==i)continue;const s=Is(null==t?void 0:t.content,e),r=Is(null==t?void 0:t.design,e);r&&!s?n[r]="string"==typeof i?i:JSON.stringify(i):s&&!r?o[s]=i:(o[e]=i,"string"!=typeof i&&"number"!=typeof i||(n[e]=String(i)))}}return{design:n,content:o,contentItems:s}}(e,t),n=Object.assign({},i.design),o=Object.assign({},i.content);let s=null;const r=gs(e.getAttribute("design"));r&&vs(r,n);const a=gs(e.getAttribute("content"));if(a){const e=ws(a,o);e&&e.length>0&&(s=e)}const d=gs(e.getAttribute("values"));if(d){const e=ws(d,o);e&&e.length>0&&(s=e)}for(const i of Array.from(e.attributes)){const e=i.name,s=e.toLowerCase();if(s.startsWith("design-")&&s.length>7){const o=os(e.slice(7));if(o&&!(o in Object.prototype)){n[Is(null==t?void 0:t.design,o)||o]=i.value}continue}if(s.startsWith("content-")&&"content-items"!==s&&s.length>8){const n=os(e.slice(8));if(n&&!(n in Object.prototype)){o[Is(null==t?void 0:t.content,n)||n]=hs(i.value)}continue}if(us(e))continue;const r=os(e);if(!r||r in Object.prototype)continue;const a=Is(null==t?void 0:t.content,r),d=Is(null==t?void 0:t.design,r);if(a&&!d)o[a]=hs(i.value);else if(d&&!a)n[d]=i.value;else{n[r]=i.value,o[r]=hs(i.value);const t=e.replace(/^data-/,"");t===r||t in Object.prototype||(n[t]=i.value)}}let l=bs(e);if(0===l.length){const t=ms(e.getAttribute("content-items"))||ms(e.getAttribute("contentitems"))||ms(e.getAttribute("items"))||s;t&&t.length>0?l=t:i.contentItems.length>0&&(l=i.contentItems)}return{design:n,content:o,contentItems:l,hasOverrides:Object.keys(n).length>0||Object.keys(o).length>0||l.length>0}}function ks(e,t){const i=null!=t?t:{},n=Ts(e,i);return n.hasOverrides?Object.assign(Object.assign({},i),{design:Object.assign(Object.assign({},i.design||{}),n.design),content:Object.assign(Object.assign({},i.content||{}),n.content),contentItems:n.contentItems.length>0?n.contentItems:i.contentItems||[]}):i}function Ss(e){var t,i;if(0===e.length)return!0;for(const n of e){if("attributes"===n.type){const e=(null===(t=n.attributeName)||void 0===t?void 0:t.toLowerCase())||"";if(!e)continue;if("data-widgetic-mounted"===e||"data-widgetic-mounting"===e||"data-widgetic-refused"===e||"data-widgetic-context-invalid"===e||"data-widgetic-overlay"===e||"data-device-restricted"===e||"data-widgetic-item"===e||"hidden"===e)continue;if("style"===e&&n.target!==(null===(i=n.target.ownerDocument)||void 0===i?void 0:i.body)&&n.target instanceof Element&&n.target.hasAttribute("data-widgetic-item"))continue;if(n.target instanceof Element&&cs(n.target))continue;return!0}if("childList"===n.type){if(n.target instanceof Element&&cs(n.target))continue;if([...Array.from(n.addedNodes),...Array.from(n.removedNodes)].some((e=>!(e instanceof Element&&cs(e)))))return!0}if("characterData"===n.type){const e=n.target.parentElement;if(e&&!cs(e))return!0}}return!1}const Cs=new WeakMap;const As="undefined"!=typeof HTMLElement?HTMLElement:class{};class Es extends As{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(),te.debug("WidgeticWidget created",{instanceId:this.instanceId})}connectedCallback(){return t(this,void 0,void 0,(function*(){var e;if(!this.isWidgetConnected){this.isWidgetConnected=!0,te.debug("WidgeticWidget connected",{instanceId:this.instanceId});try{this.setLoadingState(!0);const t=ss(this),i=null!==(e=null==t?void 0:t.id)&&void 0!==e?e:this.getAttribute("composition-id");if(!i)throw new Error("composition-id attribute is required");bs(this);const n="widget"===(null==t?void 0:t.kind)?yield Jo(i):yield Yo(i);if("refused"===n.status)throw Zo(i,n.refusal),new Error("This embed is not authorized to be shown on this website.");const o="found"===n.status?n.payload:null;if(null==o?void 0:o.embedUrl){const e=ks(this,o);return this.innerHTML="",this.appendChild(es(o.embedUrl,this.getAttribute("width")||"400",this.getAttribute("height")||"300",i,e)),void this.setWidgetReady()}yield this.loadWidgetData(i),this.widgetData&&(yield this.loadWidgetModule()),yield this.initializeWidget(),this.setupResponsiveBehavior(),this.setupEventHandling(),this.setWidgetReady()}catch(e){te.error("WidgeticWidget initialization failed",{instanceId:this.instanceId,error:e}),this.setErrorState(e)}}}))}disconnectedCallback(){this.isWidgetConnected&&(te.debug("WidgeticWidget disconnected",{instanceId:this.instanceId}),this.cleanup(),this.isWidgetConnected=!1)}attributeChangedCallback(e,t,i){if(this.isInitialized&&t!==i){switch(te.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){te.warn("Invalid theme attribute",{instanceId:this.instanceId,theme:e})}}loadWidgetData(e){return t(this,void 0,void 0,(function*(){const t=ho();this.compositionData=yield t.getComposition(e),this.widgetData=yield t.getWidget(this.compositionData.widgetId),te.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=vo();this.loadedModule=yield e.loadModule(this.widgetData),te.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,te.debug("Widget initialized successfully",{instanceId:this.instanceId})}catch(e){throw te.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})),te.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})),te.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})),te.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){te.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(),te.debug("Widget cleanup complete",{instanceId:this.instanceId})}generateInstanceId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}}class Rs{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 Rs.instance||(Rs.instance=new Rs),Rs.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,l=i=>{const o=i-a,r=Math.min(o/n,1),c=1-Math.pow(1-r,3),u=d+s*c;if(e.style.height=`${u}px`,r<1){const t=requestAnimationFrame(l);this.animationIds.set(e.id||e.tagName,t)}else e.style.height=`${t}px`,this.animationIds.delete(e.id||e.tagName)},c=requestAnimationFrame(l);this.animationIds.set(e.id||e.tagName,c)}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 xs{static getInstance(){return xs.instance||(xs.instance=new xs),xs.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.isPageUnloading=!1,this.pausedByManagerAt=new Map,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){var t;const{type:i,compositionId:n,config:o,data:s}=e;if(o&&Object.keys(o).length>0){const e=this.widgetConfigs.get(n)||{autoPause:!0,mediaType:"both",priority:5,persistState:!0,allowSimultaneous:[],autoResume:!0,autoResumeTimeout:this.defaultAutoResumeTimeout,globalVolume:!0};this.widgetConfigs.set(n,Object.assign(Object.assign({},e),o))}switch(i){case"play":this.handlePlayEvent(n,o,s);break;case"pause":this.handlePauseEvent(n,s,o);break;case"stop":case"ended":this.handleStopEvent(n);break;case"seeking":case"seeked":this.handleSeekingEvent(n,null!==(t=null==s?void 0:s.position)&&void 0!==t?t:null==s?void 0:s.currentTime,o,s);break;case"timeupdate":case"progress":case"durationchange":case"loadedmetadata":this.handleTimeUpdateEvent(n,o,s);break;case"volumechange":this.handleVolumeEvent(n,null==s?void 0:s.volume,o);break;case"trackchange":this.handleTrackChangeEvent(n,s,o);break;case"playlistchange":this.handlePlaylistChangeEvent(n,s,o)}this.emitToListeners(n,e),!1!==(null==o?void 0:o.persistState)&&this.persistState(),this.dispatchGlobalEvent(e)}getOrCreateMediaState(e,t={},i="paused",n={}){var o;const s=this.playingWidgets.get(e);if(s)return s;const r={compositionId:e,mediaType:(null==n?void 0:n.mediaType)||t.mediaType||"both",state:i,priority:t.priority||5,startedAt:Date.now(),duration:"number"==typeof(null==n?void 0:n.duration)?n.duration:void 0,position:"number"==typeof(null==n?void 0:n.position)?n.position:"number"==typeof(null==n?void 0:n.currentTime)?n.currentTime:0,title:null==n?void 0:n.title,volume:"number"==typeof(null==n?void 0:n.volume)?n.volume:void 0,playlist:null==n?void 0:n.playlist,autoResume:null===(o=t.autoResume)||void 0===o||o,lastInteraction:Date.now()};return this.playingWidgets.set(e,r),r}handlePlayEvent(e,t={},i={}){var n,o,s,r;this.pausedByManagerAt.delete(e);const a=this.playingWidgets.get(e),d=i.mediaType||t.mediaType||(null==a?void 0:a.mediaType)||"both",l=t.priority||(null==a?void 0:a.priority)||5,c="number"==typeof i.position?i.position:"number"==typeof i.currentTime?i.currentTime:null!==(n=null==a?void 0:a.position)&&void 0!==n?n:0,u={compositionId:e,mediaType:d,state:"playing",priority:l,startedAt:Date.now(),duration:"number"==typeof i.duration?i.duration:null==a?void 0:a.duration,position:c,title:null!==(o=i.title)&&void 0!==o?o:null==a?void 0:a.title,volume:"number"==typeof i.volume?i.volume:null==a?void 0:a.volume,playlist:i.playlist?Object.assign(Object.assign({},null==a?void 0:a.playlist),i.playlist):null==a?void 0:a.playlist,autoResume:null===(r=null!==(s=t.autoResume)&&void 0!==s?s:null==a?void 0:a.autoResume)||void 0===r||r,lastInteraction:Date.now()};!1!==t.autoPause&&this.pauseConflictingWidgets(e,d,l,t.allowSimultaneous||[]),this.playingWidgets.set(e,u)}handlePauseEvent(e,t={},i={}){const n=this.getOrCreateMediaState(e,i,"paused",t);n.state="paused";const o="number"==typeof(null==t?void 0:t.position)?t.position:null==t?void 0:t.currentTime;"number"==typeof o&&(n.position=o),"number"==typeof(null==t?void 0:t.duration)&&(n.duration=t.duration),"number"==typeof(null==t?void 0:t.volume)&&(n.volume=t.volume),(null==t?void 0:t.title)&&(n.title=t.title),(null==t?void 0:t.playlist)&&(n.playlist=Object.assign(Object.assign({},n.playlist),t.playlist)),n.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,i={},n={}){const o=this.getOrCreateMediaState(e,i,"paused",n);"number"==typeof t&&(o.position=t),"number"==typeof(null==n?void 0:n.duration)&&(o.duration=n.duration),(null==n?void 0:n.playlist)&&(o.playlist=Object.assign(Object.assign({},o.playlist),n.playlist)),o.lastInteraction=Date.now()}handleTimeUpdateEvent(e,t={},i={}){var n;const o="playing"===(null===(n=this.playingWidgets.get(e))||void 0===n?void 0:n.state),s=!0===(null==i?void 0:i.playing)?"playing":"paused",r=this.getOrCreateMediaState(e,t,s,i),a="number"==typeof(null==i?void 0:i.position)?i.position:null==i?void 0:i.currentTime;"number"==typeof a&&(r.position=a),"number"==typeof(null==i?void 0:i.duration)&&Number.isFinite(i.duration)&&(r.duration=i.duration),"number"==typeof(null==i?void 0:i.volume)&&(r.volume=i.volume);const d=!0===(null==i?void 0:i.playing)||"boolean"!=typeof(null==i?void 0:i.playing)&&"playing"===(null==i?void 0:i.state),l=!1===(null==i?void 0:i.playing)||"paused"===(null==i?void 0:i.state)||"stopped"===(null==i?void 0:i.state);if(d){const i=this.pausedByManagerAt.get(e);i&&Date.now()-i<500?(r.state="paused",this.sendPauseCommand(e,void 0,!1)):(r.state="playing",o||!1===t.autoPause||this.pauseConflictingWidgets(e,r.mediaType,r.priority,t.allowSimultaneous||[]))}else l&&(r.state="stopped"===(null==i?void 0:i.state)?"stopped":"paused");(null==i?void 0:i.title)&&(r.title=i.title),(null==i?void 0:i.playlist)&&(r.playlist=Object.assign(Object.assign({},r.playlist),i.playlist)),r.lastInteraction=Date.now()}handleVolumeEvent(e,t,i={}){const n=this.getOrCreateMediaState(e,i,"paused",{volume:t}),o=this.widgetConfigs.get(e)||i;n&&"number"==typeof t&&(n.lastInteraction=Date.now(),(null==o?void 0:o.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),n.volume=this.globalVolumeState.muted?0:this.globalVolumeState.volume):n.volume=t)}handleTrackChangeEvent(e,t={},i={}){const n=this.getOrCreateMediaState(e,i,"paused",t),o=(null==t?void 0:t.playlist)||Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"number"==typeof(null==t?void 0:t.currentTrack)?{currentTrack:t.currentTrack}:{}),"number"==typeof(null==t?void 0:t.trackIndex)?{currentTrack:t.trackIndex}:{}),"number"==typeof(null==t?void 0:t.totalTracks)?{totalTracks:t.totalTracks}:{}),(null==t?void 0:t.trackId)?{trackId:t.trackId}:{}),(null==t?void 0:t.trackTitle)||(null==t?void 0:t.title)?{trackTitle:t.trackTitle||t.title}:{});if(Object.keys(o).length>0&&(n.playlist=Object.assign(Object.assign({currentTrack:0,totalTracks:1},n.playlist),o),n.title=o.trackTitle||(null==t?void 0:t.title)||n.title),n.position="number"==typeof(null==t?void 0:t.position)?t.position:0,"boolean"==typeof(null==t?void 0:t.playing)){const o="playing"===n.state;n.state=t.playing?"playing":"paused",t.playing&&(this.pausedByManagerAt.delete(e),o||!1===i.autoPause||this.pauseConflictingWidgets(e,n.mediaType,n.priority,i.allowSimultaneous||[]))}n.lastInteraction=Date.now()}handlePlaylistChangeEvent(e,t={},i={}){const n=this.getOrCreateMediaState(e,i,"paused",t);(null==t?void 0:t.playlist)&&(n.playlist=Object.assign(Object.assign({},n.playlist),t.playlist),n.lastInteraction=Date.now())}pauseConflictingWidgets(e,t,i,n){const o=[];for(const[i,s]of this.playingWidgets){if(i===e||"playing"!==s.state)continue;this.isSimultaneousAllowed(s.mediaType,t,n)||o.push(i)}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)))}resolveHostElements(e){if("undefined"==typeof document)return[];const t=[`[data-widgetic-id="${e}"]`,`[data-composition-id="${e}"]`,`[composition-id="${e}"]`,`[compositionid="${e}"]`,`[composition="${e}"]`,`widgetic[composition-id="${e}"]`,`[widget="${e}"]`,`[widget-id="${e}"]`,`[widgetid="${e}"]`,`[data-widget-id="${e}"]`,`widgetic[widget="${e}"]`,`widgetic[widget-id="${e}"]`].join(", ");return Array.from(document.querySelectorAll(t))}resolveIframeTargetOrigin(e){var t;const i=e.getAttribute("src")||e.src;if(i)try{const e=new URL(i,"undefined"!=typeof window&&(null===(t=window.location)||void 0===t?void 0:t.href)?window.location.href:"https://widgetic.com").origin;if(e&&"null"!==e)return e}catch(e){}return"*"}dispatchCommandToHostAndIframe(e,t){var i;const n=this.resolveHostElements(e);if(0===n.length)return!1;for(const e of n){const n="iframe"===e.tagName.toLowerCase()?e:e.querySelector("iframe");if(null==n?void 0:n.contentWindow){const e=this.resolveIframeTargetOrigin(n);try{n.contentWindow.postMessage(t,e)}catch(e){try{n.contentWindow.postMessage(t,"*")}catch(e){}}}e.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:t}));const o=e.querySelector("[data-widgetic-direct]"),s=null===(i=null==o?void 0:o.shadowRoot)||void 0===i?void 0:i.querySelector(".widgetic-direct-target");s&&s.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:t,bubbles:!0,composed:!0}))}return!0}sendPauseCommand(e,t,i=!0){if(i){this.pausedByManagerAt.set(e,Date.now());const t=this.playingWidgets.get(e);t&&(t.state="paused")}this.dispatchCommandToHostAndIframe(e,Object.assign({type:"widgetic:media:command",command:"pause",compositionId:e},"number"==typeof t?{position:t}:{}))}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){const t=this.playingWidgets.get(e);this.dispatchCommandToHostAndIframe(e,Object.assign({type:"widgetic:media:command",command:"play",compositionId:e},"number"==typeof(null==t?void 0:t.position)?{position:t.position}:{}))}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(){var e;if("undefined"!=typeof localStorage)try{const t=localStorage.getItem(this.storageKey);if(t){const i=JSON.parse(t);if(i.version!==this.storageVersion)return void this.clearPersistedState();const n=864e5;if(i.timestamp&&Date.now()-i.timestamp>n)return void this.clearPersistedState();const o=[];for(const[e,t]of Object.entries(i.playingWidgets||{})){const e=t;e.compositionId&&e.mediaType&&e.state&&o.push(e)}const s=null===(e=o.filter((e=>"playing"===e.state)).sort(((e,t)=>{const i=e.lastInteraction||e.startedAt||0,n=t.lastInteraction||t.startedAt||0;return n!==i?n-i:(t.priority||5)-(e.priority||5)}))[0])||void 0===e?void 0:e.compositionId;for(const e of o)"playing"===e.state&&e.compositionId!==s&&(e.state="paused"),this.playingWidgets.set(e.compositionId,e)}}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",(()=>{if(document.hidden&&!this.isPageUnloading){const e=this.getPlayingWidgets();for(const t of e)this.sendPauseCommand(t.compositionId,t.position,!1)}}))}setupUnloadHandler(){if("undefined"==typeof window)return;const e=()=>{this.isPageUnloading=!0,this.persistState()};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e)}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={}){var t,i;if(!this.autoResumeEnabled)return;const{autoResumePlayback:n=!0,maxStateAge:o=this.defaultAutoResumeTimeout,respectTimeouts:s=!0}=e,r=Date.now(),a=[];for(const[e,d]of this.playingWidgets){const l=this.widgetConfigs.get(e)||{persistState:!0,autoResume:null===(t=d.autoResume)||void 0===t||t};(null!==(i=l.autoResume)&&void 0!==i?i:d.autoResume)&&!1!==l.persistState&&d.lastInteraction&&(!s||r-d.lastInteraction<=(l.autoResumeTimeout||o))&&("playing"===d.state||n&&"paused"===d.state)&&a.push(d)}if(a.length>0){a.sort(((e,t)=>e.priority!==t.priority?t.priority-e.priority:(t.lastInteraction||0)-(e.lastInteraction||0)));let e=!1;for(const t of a)n&&"playing"===t.state&&!e?(e=!0,this.resumeWidget(t.compositionId)):this.sendRestoreStateCommand(t.compositionId,Object.assign(Object.assign({},t),{state:"paused"}))}}resumeWidget(e){const t=this.playingWidgets.get(e);if(!t)return!1;if("playing"===t.state){this.pausedByManagerAt.delete(e);const i=this.widgetConfigs.get(e);!1!==(null==i?void 0:i.autoPause)&&this.pauseConflictingWidgets(e,t.mediaType,t.priority,(null==i?void 0:i.allowSimultaneous)||[])}return this.sendRestoreStateCommand(e,t),"playing"===t.state?setTimeout((()=>{var i;"playing"===(null===(i=this.playingWidgets.get(e))||void 0===i?void 0:i.state)&&this.sendPlayCommand(e,t.position)}),100):"paused"===t.state&&setTimeout((()=>{var i;"playing"!==(null===(i=this.playingWidgets.get(e))||void 0===i?void 0:i.state)&&this.sendPauseCommand(e,t.position,!1)}),100),!0}sendRestoreStateCommand(e,t){const i={type:"widgetic:media:command",command:"restore",compositionId:e,state:{state:t.state,playing:"playing"===t.state,position:"number"==typeof t.position?t.position:0,volume:"number"==typeof t.volume?t.volume:1,title:t.title,playlist:t.playlist,duration:t.duration}};this.dispatchCommandToHostAndIframe(e,i)}sendPlayCommand(e,t){const i={type:"widgetic:media:command",command:"play",compositionId:e,position:t};this.dispatchCommandToHostAndIframe(e,i)}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);!1!==(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){const i={type:"widgetic:media:command",command:"setVolume",compositionId:e,volume:Math.max(0,Math.min(1,t))};this.dispatchCommandToHostAndIframe(e,i)}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 Ms=null;function Ws(){return Ms||(Ms=xs.getInstance()),Ms}var Ds=Object.freeze({__proto__:null,MediaManager:xs,getMediaManager:Ws,resetMediaManager:function(){Ms&&(Ms.destroy(),Ms=null)}});class Os{static getInstance(){return Os.instance||(Os.instance=new Os),Os.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,s=Object.assign(Object.assign({contentType:"custom",persistState:!0,autoResume:!0,debounceDelay:500,trackMetadata:!0},this.widgetConfigs.get(i)),n);switch(void 0!==s.autoResumePosition&&void 0===n.autoResume&&(s.autoResume=s.autoResumePosition),this.widgetConfigs.set(i,s),t){case"position":case"navigate":this.handlePositionChangeEvent(i,s,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),!1!==s.persistState&&this.persistState(),this.dispatchGlobalEvent(e)}handlePositionChangeEvent(e,t,i={}){var n,o,s,r,a,d,l,c,u,h;const g=this.contentStates.get(e),p="number"==typeof(null==i?void 0:i.currentIndex)?i.currentIndex:"number"==typeof(null==i?void 0:i.index)?i.index:null!==(n=null==g?void 0:g.currentIndex)&&void 0!==n?n:0,m="number"==typeof(null==i?void 0:i.totalItems)?i.totalItems:"number"==typeof(null==i?void 0:i.total)?i.total:null!==(o=null==g?void 0:g.totalItems)&&void 0!==o?o:0,f=void 0!==(null==i?void 0:i.metadata)||void 0!==(null==g?void 0:g.metadata)?Object.assign(Object.assign({},null==g?void 0:g.metadata),null==i?void 0:i.metadata):void 0,v={compositionId:e,contentType:t.contentType||(null==g?void 0:g.contentType)||"custom",currentIndex:p,totalItems:m,currentItemId:null!==(r=null!==(s=null==i?void 0:i.currentItemId)&&void 0!==s?s:null==i?void 0:i.itemId)&&void 0!==r?r:null==g?void 0:g.currentItemId,currentItemTitle:null!==(l=null!==(d=null!==(a=null==i?void 0:i.currentItemTitle)&&void 0!==a?a:null==i?void 0:i.itemTitle)&&void 0!==d?d:null==i?void 0:i.title)&&void 0!==l?l:null==g?void 0:g.currentItemTitle,lastUpdated:Date.now(),autoResume:null===(h=null!==(u=null!==(c=t.autoResume)&&void 0!==c?c:t.autoResumePosition)&&void 0!==u?u:null==g?void 0:g.autoResume)||void 0===h||h,lastInteraction:Date.now(),metadata:f};this.contentStates.set(e,v)}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={}){var t,i,n,o;if(!this.autoResumeEnabled)return;const{autoResumePosition:s=!0,maxStateAge:r=this.defaultAutoResumeTimeout,respectTimeouts:a=!0}=e,d=Date.now(),l=[];for(const[e,c]of this.contentStates){const u=this.widgetConfigs.get(e),h=null!==(n=null!==(i=null!==(t=null==u?void 0:u.autoResume)&&void 0!==t?t:null==u?void 0:u.autoResumePosition)&&void 0!==i?i:c.autoResume)&&void 0!==n&&n,g=null===(o=null==u?void 0:u.persistState)||void 0===o||o;h&&g&&c.lastInteraction&&(!a||d-c.lastInteraction<=((null==u?void 0:u.autoResumeTimeout)||r))&&s&&l.push(c)}l.length>0&&l.forEach((e=>{this.resumeWidgetPosition(e.compositionId)}))}resumeWidgetPosition(e){const t=this.contentStates.get(e);return!!t&&(this.sendRestorePositionCommand(e,t),!0)}resolveHostElement(e){return"undefined"==typeof document?null:document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"], [composition-id="${e}"], widgetic[composition-id="${e}"], [widget="${e}"], [widget-id="${e}"], widgetic[widget="${e}"], widgetic[widget-id="${e}"]`)}resolveIframeTargetOrigin(e){var t;const i=e.getAttribute("src")||e.src;if(i)try{const e=new URL(i,"undefined"!=typeof window&&(null===(t=window.location)||void 0===t?void 0:t.href)?window.location.href:"https://widgetic.com").origin;if(e&&"null"!==e)return e}catch(e){}return"*"}sendRestorePositionCommand(e,t){var i;const n=this.resolveHostElement(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}},s="iframe"===n.tagName.toLowerCase()?n:n.querySelector("iframe");if(null==s?void 0:s.contentWindow){const e=this.resolveIframeTargetOrigin(s);try{s.contentWindow.postMessage(o,e)}catch(e){try{s.contentWindow.postMessage(o,"*")}catch(e){}}}n.dispatchEvent(new CustomEvent("widgetic:content:command",{detail:o}));const r=n.querySelector("[data-widgetic-direct]"),a=null===(i=null==r?void 0:r.shadowRoot)||void 0===i?void 0:i.querySelector(".widgetic-direct-target");a&&a.dispatchEvent(new CustomEvent("widgetic:content:command",{detail:o,bubbles:!0,composed:!0}))}}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);!1!==(null==o?void 0:o.persistState)&&this.persistState()}}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 Ls=null;function Us(){return Ls||(Ls=Os.getInstance()),Ls}class Ps{constructor(){this.autoScaleManager=Rs.getInstance(),"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-widget")||(customElements.define("widgetic-widget",Es),te.info("WidgeticWidget custom element registered")))}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,l=document.createElement("widgetic-widget");if(l.setAttribute("composition-id",t),l.setAttribute("width",String(i)),l.setAttribute("height",String(n)),l.setAttribute("resize",o),"boolean"==typeof s?l.setAttribute("autoscale",s?"true":"false"):s&&"object"==typeof s?(l.setAttribute("autoscale","true"),void 0!==s.minHeight&&l.setAttribute("autoscale-min-height",String(s.minHeight)),void 0!==s.maxHeight&&l.setAttribute("autoscale-max-height",String(s.maxHeight)),void 0!==s.debounceDelay&&l.setAttribute("autoscale-debounce",String(s.debounceDelay)),void 0!==s.threshold&&l.setAttribute("autoscale-threshold",String(s.threshold)),void 0!==s.animate&&l.setAttribute("autoscale-animate",String(s.animate)),void 0!==s.animationDuration&&l.setAttribute("autoscale-animation-duration",String(s.animationDuration))):l.setAttribute("autoscale","false"),l.setAttribute("adaptive",String(r)),a&&Object.keys(a).length>0){Ws().registerWidget(t,a),this.setupCustomElementMediaListener(l,t)}if(d&&Object.keys(d).length>0){Us().registerWidget(t,d),this.setupCustomElementContentListener(l,t)}return{id:`custom-${t}-${Date.now()}`,element:l,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:()=>{l._mediaCommandCleanup&&l._mediaCommandCleanup(),l._mediaObserverCleanup&&l._mediaObserverCleanup(),l._contentPositionCleanup&&l._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=Ws(),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=Us(),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)}}}var _s=Object.freeze({__proto__:null,CustomElementRenderer:Ps});const zs={close:"Close",closeOverlay:"Close overlay",interactiveWidget:"Interactive widget"},qs=new Map([["fr",{close:"Fermer",closeOverlay:"Fermer la fenêtre",interactiveWidget:"Widget interactif"}],["de",{close:"Schließen",closeOverlay:"Fenster schließen",interactiveWidget:"Interaktives Widget"}],["es",{close:"Cerrar",closeOverlay:"Cerrar ventana",interactiveWidget:"Widget interactivo"}],["pt",{close:"Fechar",closeOverlay:"Fechar janela",interactiveWidget:"Widget interativo"}],["nl",{close:"Sluiten",closeOverlay:"Venster sluiten",interactiveWidget:"Interactieve widget"}],["da",{close:"Luk",closeOverlay:"Luk vinduet",interactiveWidget:"Interaktiv widget"}],["sv",{close:"Stäng",closeOverlay:"Stäng fönstret",interactiveWidget:"Interaktiv widget"}],["zh",{close:"关闭",closeOverlay:"关闭窗口",interactiveWidget:"交互式小组件"}],["ar",{close:"إغلاق",closeOverlay:"إغلاق النافذة",interactiveWidget:"ويجت تفاعلي"}],["he",{close:"סגירה",closeOverlay:"סגירת החלון",interactiveWidget:"וידג'ט אינטראקטיבי"}],["fa",{close:"بستن",closeOverlay:"بستن پنجره",interactiveWidget:"ویجت تعاملی"}],["ur",{close:"بند کریں",closeOverlay:"ونڈو بند کریں",interactiveWidget:"انٹرایکٹو ویجٹ"}]]);function js(e,t=function(){var e,t;return"undefined"==typeof document?"":(null===(e=document.body)||void 0===e?void 0:e.getAttribute("lang"))||(null===(t=document.documentElement)||void 0===t?void 0:t.getAttribute("lang"))||""}()){const i=function(e){var t,i;const n=(null!=e?e:"").trim().replace(/_/g,"-").toLowerCase().split("-"),o="iw"===n[0]?"he":null!==(t=n[0])&&void 0!==t?t:"",s=null!==(i=n[1])&&void 0!==i?i:"";return("zh"!==o||"tw"!==s&&"hk"!==s&&"hant"!==s)&&qs.has(o)?o:null}(t),n=null===i?void 0:qs.get(i);return(null!=n?n:zs)[e]}qs.keys();class $s{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(),te.info("WidgeticMessenger initialized",{securityOptions:this.securityOptions})}setupAllowedOrigins(e){en.CLIENT_URL&&this.allowedOrigins.add(en.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,te.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 te.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)?(te.warn("Message signature validation failed",{instanceId:t.instanceId}),null):t:(te.warn("Invalid message structure",{message:t}),null)}catch(t){return te.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(te.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){te.error("Message handler error",{error:e,instanceId:t.instanceId})}else te.debug("No handler for message",{instanceId:t.instanceId,type:t.type})}handleHeartbeat(e){te.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){te.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 Ar})).then((({getSecurityManager:o})=>{const s=o().validateTextFieldUpdate(e.instanceId,t,i,n);if(!s.allowed)return te.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}));te.debug("Text field change received",{instanceId:e.instanceId,fieldId:t,textLength:i.length,sanitized:!(!s.sanitizedText||s.sanitizedText===i)}),Promise.resolve().then((function(){return ed})).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=>{te.warn("Failed to handle text field change",{error:t,instanceId:e.instanceId})}))})).catch((t=>{te.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}))):te.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&&(te.debug("Dispatching custom event",{instanceId:e.instanceId,eventName:t,subscriberCount:s.size}),s.forEach((o=>{try{o(i,n)}catch(i){te.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){te.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"))):te.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),te.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),te.debug("Message handler unregistered",{instanceId:e})}sendMessage(e,t){const i=document.querySelector(`[data-widgetic-id="${e}"]`);if(!i||!i.contentWindow)return te.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),"*"),te.debug("Message sent",{instanceId:e,type:o.type,sequence:n})}catch(i){te.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)):te.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),te.debug("Heartbeat started",{instanceId:e,interval:this.securityOptions.heartbeatInterval})}stopHeartbeat(e){const t=this.heartbeatIntervals.get(e);t&&(clearInterval(t),this.heartbeatIntervals.delete(e),te.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(),te.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 ed}));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 ed}));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 ed}));return t().getTextField(e,i)})),clearTextField:i=>t(this,void 0,void 0,(function*(){const{getTextFieldManager:t}=yield Promise.resolve().then((function(){return ed}));t().clearTextField(e,i)})),getTextFields:()=>t(this,void 0,void 0,(function*(){const{getTextFieldManager:t}=yield Promise.resolve().then((function(){return ed}));return t().getWidgetTextFields(e)})),clearAllTextFields:()=>t(this,void 0,void 0,(function*(){const{getTextFieldManager:t}=yield Promise.resolve().then((function(){return ed}));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),te.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),te.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"}),te.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"}),te.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)})),te.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),te.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),te.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 Bs=null;function Ns(e){return Bs||(Bs=new $s(e)),Bs}var Fs=Object.freeze({__proto__:null,WidgeticMessenger:$s,getMessenger:Ns,resetMessenger:function(){Bs&&(Bs.cleanup(),Bs=null)}});class Ks{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),te.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),te.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 l,c;switch(o){case"fill-width":l=a,c=l/e.aspectRatio,s&&c>d&&(c=d,l=c*e.aspectRatio);break;case"fill-height":c=d,l=c*e.aspectRatio,s&&l>a&&(l=a,c=l/e.aspectRatio);break;case"fixed":default:l=e.originalWidth,c=e.originalHeight;break;case"fixed-height":l=a,c=e.originalHeight;break;case"fixed-width":l=e.originalWidth,c=d;break;case"allow-scale-down":const t=a/e.originalWidth,i=d/e.originalHeight,n=Math.min(1,Math.min(t,i));l=e.originalWidth*n,c=e.originalHeight*n;break;case"fill":l=a,c=d}this.setElementSize(t,l,c,n),this.options.enableAdaptive&&n.adaptive&&this.handleAdaptiveBreakpoint(e,a),te.debug("Resize mode applied",{widgetId:e.widgetId,resizeMode:o,containerSize:{width:a,height:d},newSize:{width:l,height:c}})}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 Hs=null;class Vs{constructor(){this.observers=new Map,this.callbacks=new Map,this.currentStates=new Map,this.debounceTimers=new Map,"undefined"==typeof ResizeObserver&&te.warn("ResizeObserver not available, responsive breakpoints will not work")}registerWidget(e,t,i,n){if("undefined"==typeof ResizeObserver)return void te.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),te.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),te.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 te.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),te.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),te.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),te.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);te.debug("ResponsiveManager cleanup complete")}}let Gs=null;function Xs(){return Gs||(Gs=new Vs),Gs}class Ys{constructor(){this.messageQueue=new Map,this.iframeRegistry=new Map,this.loadingTimeouts=new Map,this.autoScaleManager=Rs.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:l=!0,sandbox:c=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,c,u),p.width=i.toString(),p.height=n.toString(),p.frameBorder="0",p.scrolling="no",l&&(p.allowFullscreen=!0,p.setAttribute("allowfullscreen","")),p.title=`Widgetic Widget ${t}`,p.setAttribute("aria-label",`${js("interactiveWidget")}: ${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=Ks.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 Ks({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(te.info("Enhanced iframe widget rendered successfully",{compositionId:t,size:{width:i,height:n},resize:o,autoscale:s,responsive:a,sandbox:c.join(" "),features:u.join("; ")}),m.media&&Object.keys(m.media).length>0){Ws().registerWidget(t,m.media),this.setupIframeMediaListener(p,t)}if(e.content&&Object.keys(e.content).length>0){Us().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 te.error("Enhanced iframe widget rendering failed",{compositionId:t,error:e}),this.removeLoadingIndicator(d),e}}))}renderWidgets(e){return t(this,void 0,void 0,(function*(){te.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{te.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 te.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||[en.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=`${en.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 nn();o.set("apiKey",e)}catch(e){te.warn("Failed to get auth token for iframe",e),en.API_KEY&&o.set("apiKey",en.API_KEY)}const s=`${n}?${o.toString()}`;return te.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)},te.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++,te.warn(`Iframe loading failed, retrying (${s}/${o})`,{compositionId:t}),setTimeout((()=>{e.src=e.src+"&retry="+s}),1e3*s)):(te.error("Iframe loading failed after retries",{compositionId:t,retryCount:o}),this.handleIframeFallback(e,t))},a=setTimeout((()=>{te.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)),te.debug("Iframe loaded successfully",{compositionId:t})})),e.addEventListener("error",(()=>{te.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=Ns({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:sn(),timestamp:Date.now(),sdkVersion:"2.0",mode:"iframe"},timestamp:Date.now(),version:"1.0"}),te.debug("Initial config sent to iframe",{compositionId:t})})),e.__messenger=n,e.__messagingCompositionId=t,te.debug("Enhanced iframe messaging setup complete",{compositionId:t})}handleEnhancedIframeMessage(e,t){switch(te.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:te.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})),te.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})),te.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})),te.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})),te.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})),te.debug("Iframe interaction event",{instanceId:t.instanceId,eventType:t.payload.type})}sendMessageToIframe(e,t,i){Ns().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),te.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=Xs(),s=Ns(),r={breakpoint:n,debounceDelay:150},a=`responsive-${i}`;o.registerWidget(a,t,r,(t=>{te.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,te.info("Responsive monitoring enabled for iframe",{compositionId:i,breakpoint:n,containerId:a})}setupIframeMediaListener(e,t){const i=Ws(),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","seeked","timeupdate","progress","volumechange","trackchange","playlistchange"].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.detail||n.data.payload||n.data.data||{}})}}};window.addEventListener("message",n),e._mediaListenerCleanup=()=>{window.removeEventListener("message",n)}}setupIframeContentListener(e,t){const i=Us(),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)}}}let Js=null;var Qs=Object.freeze({__proto__:null,IframeRenderer:Ys,getIframeRenderer:function(){return Js||(Js=new Ys),Js}});class Zs{constructor(){this.batchClient=ho(),this.moduleLoader=vo(),this.customElementRenderer=new Ps,this.iframeRenderer=new Ys,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 l=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(l)).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 er=null;function tr(){return er||(er=new Zs),er}var ir=Object.freeze({__proto__:null,WidgetRenderer:Zs,getWidgetRenderer:tr,resetWidgetRenderer:function(){er&&er.cleanupAll(),er=null}});function nr(){var e;try{if("undefined"!=typeof document){const e=document.querySelectorAll("script[src*='embed-sdk']");for(const t of Array.from(e))if("off"===t.getAttribute("data-widgetic-telemetry"))return!1}if("undefined"!=typeof window&&!1===(null===(e=window.WidgeticConfig)||void 0===e?void 0:e.telemetry))return!1}catch(e){}return!0}class or{constructor(e={}){this.metrics=[],this.webVitals={},this.widgetMetrics=new Map,this.isTracking=!1,this.config=Object.assign({enableTracking:gn.ENABLE_PERFORMANCE_TRACKING,enableWebVitals:!0,enableWidgetMetrics:!0,enableResourceTracking:!0,enableBudgetMonitoring:!0,sampleRate:gn.PERFORMANCE_SAMPLE_RATE,maxMetricsBuffer:gn.MAX_METRICS_BUFFER,axiomApiEndpoint:gn.AXIOM_API_ENDPOINT,statsigApiEndpoint:gn.STATSIG_API_ENDPOINT,budgets:[{metric:"lcp",threshold:gn.LCP_THRESHOLD,warningThreshold:gn.LCP_WARNING_THRESHOLD,enabled:!0},{metric:"fid",threshold:gn.FID_THRESHOLD,warningThreshold:gn.FID_WARNING_THRESHOLD,enabled:!0},{metric:"cls",threshold:gn.CLS_THRESHOLD,warningThreshold:gn.CLS_WARNING_THRESHOLD,enabled:!0},{metric:"widget-load",threshold:gn.WIDGET_LOAD_THRESHOLD,warningThreshold:gn.WIDGET_LOAD_WARNING_THRESHOLD,enabled:!0},{metric:"bundle-size",threshold:gn.BUNDLE_SIZE_THRESHOLD,warningThreshold:gn.BUNDLE_SIZE_WARNING_THRESHOLD,enabled:!0}]},e),this.navigationStart=performance.now(),this.init()}init(){"undefined"!=typeof window&&this.config.enableTracking&&nr()&&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;if(!nr())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 sr=null;function rr(e){return sr||(sr=new or(e)),sr}function ar(e={}){return sr=new or(e),sr}var dr=Object.freeze({__proto__:null,PerformanceMonitor:or,getPerformanceMonitor:rr,initializePerformanceMonitoring:ar});class lr{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),te.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),te.debug("Portal host created",{target:this.options.target,host:e})),e}mount(e){this.destroyed?te.warn("Cannot mount content to destroyed portal"):this.container?(this.content&&this.unmount(),e.style.pointerEvents="auto",this.content=e,this.container.appendChild(e),te.debug("Content mounted to portal",{content:e})):te.error("Portal container not available")}unmount(){this.content&&this.container&&this.container.contains(this.content)&&(this.container.removeChild(this.content),this.content=null,te.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,te.debug("Portal destroyed")}}getContainer(){return this.container}isDestroyed(){return this.destroyed}updateOptions(e){this.destroyed?te.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"))),te.debug("Portal options updated",{options:this.options}))}}function cr(e){return new lr(e)}const ur=e=>null!==e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"===Object.prototype.toString.call(e);function hr(e){if(Array.isArray(e))return e.map(hr);if(!ur(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(hr):ur(n)?hr(n):n}return t}function gr(e){if(Array.isArray(e))return e.map(gr);if(!ur(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(gr):ur(n)?gr(n):n}return t}class pr{constructor(){this.sessionCache=null,this.sessionCacheExpiry=0,this.ownershipCache=new Map;const e=on(),t=new re({basePath:e.basePath,apiKey:e.apiKey,credentials:"include"});this.authApi=new $i(t),this.compositionsApi=new Ni(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=hr(yield this.authApi.getSession());return e&&e.accessToken&&e.user?(this.sessionCache=e,this.sessionCacheExpiry=Date.now()+3e5,te.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 te.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=hr(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),te.debug("Composition ownership checked",{compositionId:e,isOwner:s,userId:n.session.user.id,compositionCreatorId:o.creatorId}),r}catch(t){te.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(),te.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 en.ENABLE_EDITING}}let mr=null;function fr(){return mr||(mr=new pr),mr}class vr{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"===en.NODE_ENV?en.CLIENT_URL:`${en.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,te.info("UI SDK loaded successfully",{basePath:this.config.basePath,version:this.config.version}),this.sdkInstance}catch(e){throw te.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?(te.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),te.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)),te.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){te.warn("Error during UI SDK cleanup",{error:e})}this.sdkInstance=null}this.loadPromise=null,this.isLoading=!1,window.WidgeticUI&&delete window.WidgeticUI,te.debug("UI SDK cleanup complete")}))}preload(){return t(this,void 0,void 0,(function*(){try{yield this.loadUISdk(),te.debug("UI SDK preloaded successfully")}catch(e){te.warn("UI SDK preload failed",{error:e})}}))}}let yr=null;function wr(e){return yr||(yr=new vr(e)),yr}class br{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=fr(),n=yield t.checkCompositionOwnership(i);n.canEdit?(yield this.createOverlay(e,i,!0),te.debug("Editor overlay added for owned composition",{compositionId:i})):te.debug("Editor overlay not added - user cannot edit",{compositionId:i,reason:n.error})}catch(e){te.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),te.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 lr({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 te.warn("No editor session found",{compositionId:e});if(t.isOpen)return void te.debug("Editor already open",{compositionId:e});te.info("Opening composition editor",{compositionId:e});const i=wr(),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=Ns().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")}te.info("Composition editor opened successfully",{compositionId:e})}catch(t){te.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{te.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),te.info("Composition saved successfully",{compositionId:e})}catch(t){te.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){te.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=wr().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,te.info("Editor closed",{compositionId:e})}catch(t){te.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),te.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);te.debug("Editor overlay cleanup complete")}}let Ir=null;function Tr(e){return Ir||(Ir=new br(e)),Ir}var kr=Object.freeze({__proto__:null,EditorOverlay:br,getEditorOverlay:Tr,resetEditorOverlay:function(){Ir&&(Ir.cleanup(),Ir=null)}});class Sr{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(),te.info("[SecurityManager] Initialized with config:",this.config)}static getInstance(e){return Sr.instance||(Sr.instance=new Sr(e)),Sr.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 te.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 te.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){te.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),te.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);te.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);te.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),te.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(),te.info("[SecurityManager] Destroyed")}}function Cr(e){return Sr.getInstance(e)}var Ar=Object.freeze({__proto__:null,SecurityManager:Sr,getSecurityManager:Cr});class Er{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,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=Sr.getInstance(this.config),this.initializeCSP(),this.initializeDataSecurity(),this.initializeContentFilters(),this.initializeThreatDetection(),this.initializePrivacyControls(),te.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 Er.instance||(Er.instance=new Er(e)),Er.instance}initializeCSP(){this.config.csp&&(this.cspNonce=this.generateNonce(),this.setupCSPDirectives(),this.applyCSP(),te.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[data-widgetic-csp]");i||(i=document.createElement("meta"),i.httpEquiv="Content-Security-Policy",i.setAttribute("data-widgetic-csp","1"),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,te.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"]),te.info("[AdvancedSecurityManager] Data encryption initialized")}catch(e){te.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)})),te.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)})),te.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(),te.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){te.warn("[AdvancedSecurityManager] Failed to parse existing consent:",e)}}}initializeDataSubjectRights(){te.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 te.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){te.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 te.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 l=Math.min(10,d);o+=l,l>=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:l,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 te.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);te[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}),te.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"}}}var Rr=Object.freeze({__proto__:null,AdvancedSecurityManager:Er,getAdvancedSecurityManager:function(e){return Er.getInstance(e)}});class xr{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=cr({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){te.warn("Native fullscreen failed, using CSS fullscreen",{error:e})}te.info("Widget entered fullscreen mode",{widgetId:e})}catch(t){throw te.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),te.info("Widget exited fullscreen mode",{widgetId:e})}catch(t){throw te.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=cr({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),te.info("Widget shown in overlay mode",{widgetId:e})}catch(t){throw te.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),te.info("Widget overlay hidden",{widgetId:e})}catch(t){throw te.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),te.info("Widget opened in popup",{widgetId:e}),r}catch(t){throw te.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,te.info("Widget popup closed",{widgetId:e})}catch(t){te.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.setAttribute("aria-label",js("close")),t.style.cssText="\n position: absolute;\n top: 20px;\n right: 20px;\n background: rgba(0, 0, 0, 0.7);\n color: white;\n border: none;\n border-radius: 50%;\n width: 40px;\n height: 40px;\n font-size: 20px;\n cursor: pointer;\n z-index: 100002;\n ",t.addEventListener("click",e),t}createOverlayContainer(e,t){const i=document.createElement("div");i.className="widgetic-overlay-container",i.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n background: ${t.backdrop?"rgba(0, 0, 0, 0.8)":"transparent"};\n `;const n=document.createElement("div");if(n.className="overlay-content",n.style.cssText=`\n max-width: ${t.maxWidth||"90vw"};\n max-height: ${t.maxHeight||"90vh"};\n background: white;\n border-radius: 8px;\n overflow: hidden;\n position: relative;\n `,t.showCloseButton){const t=this.createExitButton((()=>this.hideOverlay(e)));n.appendChild(t)}return i.appendChild(n),i}styleOverlayWidget(e,t){const i="mixed"===t.embedTarget&&!t.keepDimensions;let n=t.width||"100%",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 Mr=null;function Wr(e){return Mr||(Mr=new xr(e)),Mr}var Dr=Object.freeze({__proto__:null,DisplayManager:xr,getDisplayManager:Wr,resetDisplayManager:function(){Mr&&(Mr.cleanupAll(),Mr=null)}});class Or{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 Lr{constructor(){this.deviceInfo=null}static getInstance(){return Lr.instance||(Lr.instance=new Lr),Lr.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 te.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?(te.debug("Widget restricted on mobile device"),!1):!(i.isDesktop&&!t)||(te.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 Ur(){return Lr.getInstance()}function Pr(e=!0,t=!0){return Ur().checkDeviceRestrictions(e,t)}class _r{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&&(te.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),te.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}),te.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++,te.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),te.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,te.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),te.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),te.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),te.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,te.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,te.debug("ScrollTrigger destroyed",{widgetId:this.widgetId}))}}class zr{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&&(te.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)),te.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)),te.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),te.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()),te.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,te.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,te.debug("ExitIntentTrigger destroyed",{widgetId:this.widgetId}))}}const qr={"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 jr{constructor(){this.storageKey="widgetic-overlay-views",this.storageVersion="1.0"}static getInstance(){return jr.instance||(jr.instance=new jr),jr.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 te.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),te.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 te.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){te.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),te.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&&te.debug(`[RecurrenceManager] Cleaned up ${e.length} old view records`)}}class $r{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=jr.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(te.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),te.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 _r({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 zr({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;te.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;te.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 te.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=cr({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),te.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,te.debug("Widget returned to original position",{widgetId:this.widgetId}),this.dispatchEvent("overlay-hidden",{mode:this.mode}))}hideWidget(){this.element.style.display="none"}createOverlayContainer(){var e,t,i,n,o;const s=document.createElement("div");s.className="widgetic-trigger-overlay";const r=(null===(e=this.config.overlay)||void 0===e?void 0:e.position)||"bottom-right",a=(null===(t=this.config.overlay)||void 0===t?void 0:t.offset)||{x:20,y:20},d=this.hasOverlayBackground(),l=!!(null===(i=this.config.overlay)||void 0===i?void 0:i.fullWidth),c=this.getOverlayStyles(r,a,this.getOverlayZIndex(),l);if(s.style.cssText=c,d&&this.applyBackgroundStyling(s),null===(n=this.config.overlay)||void 0===n?void 0:n.closeButton){const e=this.createCloseButton(d,l);s.appendChild(e)}return(null===(o=this.config.overlay)||void 0===o?void 0:o.animation)&&s.classList.add(`widgetic-trigger-overlay-${this.config.overlay.animation}`),this.applyOverlayWidgetStyling(s),s}applyBackgroundStyling(e){var t,i;const n=null===(t=this.config.overlay)||void 0===t?void 0:t.background,o=(null==n?void 0:n.color)||"#000000",s=null!==(i=null==n?void 0:n.opacity)&&void 0!==i?i:.5,r=document.createElement("div");r.className="widgetic-trigger-overlay-backdrop",r.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background-color: ${o};\n opacity: ${s};\n pointer-events: auto;\n z-index: -1;\n `,r.addEventListener("click",(e=>{e.target===r&&this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),e.insertBefore(r,e.firstChild),e.classList.add("widgetic-trigger-overlay-has-background")}hasOverlayBackground(){var e,t,i;return!(!(null===(t=null===(e=this.config.overlay)||void 0===e?void 0:e.background)||void 0===t?void 0:t.enabled)&&!(null===(i=this.config.overlay)||void 0===i?void 0:i.backdrop))}getOverlayZIndex(){var e;const t=null===(e=this.config.overlay)||void 0===e?void 0:e.zIndex;return"number"!=typeof t||!Number.isFinite(t)||t<=0?99999999:Math.min(Math.floor(t),Sn)}getOverlayStyles(e,t,i,n){const[o,s]=qr[e]||qr["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",js("closeOverlay")),i.setAttribute("type","button");const n=this.createCloseSVG();i.appendChild(n);const o=t?"\n position: absolute;\n top: 8px;\n right: 8px;\n ":e?"\n position: absolute;\n top: 20px;\n right: 20px;\n ":"\n position: absolute;\n top: -16px;\n right: -16px;\n ";return i.style.cssText=o+"\n width: 32px;\n height: 32px;\n border-radius: 50%;\n border: none;\n background: #000000;\n color: #ffffff;\n cursor: pointer;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n transition: all 0.2s ease;\n ",i.addEventListener("mouseenter",(()=>{i.style.backgroundColor="#333333",i.style.transform="scale(1.1)"})),i.addEventListener("mouseleave",(()=>{i.style.backgroundColor="#000000",i.style.transform="scale(1)"})),i.addEventListener("click",(e=>{e.stopPropagation(),this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),i}createCloseSVG(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","16"),e.setAttribute("height","16"),e.setAttribute("viewBox","0 0 16 16"),e.setAttribute("fill","none"),e.style.pointerEvents="none";const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M12 4L4 12M4 4l8 8"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),e.appendChild(t),e}dispatchTriggerEvent(e,t,i){this.dispatchEvent(`trigger-${e}`,{triggerType:t,triggerData:i,mode:this.mode,isInOverlay:this.isInOverlay})}dispatchEvent(e,t){const i=new CustomEvent(`widgetic:${e}`,{detail:Object.assign(Object.assign({widgetId:this.widgetId},t),{source:"trigger-manager"})});document.dispatchEvent(i)}updateConfig(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)})),te.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),te.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,te.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 Br=Object.freeze({__proto__:null,TriggerManager:$r});class Nr{constructor(e={}){var t,i;this.widgets=new Map,this.widgetConfigs=new Map,this.compositionData=new Map,this.triggerManagers=new Map,this.compositionWidgets=new Map,this.eventListeners=new Map,this.errorHandlers=new Set,this.isInitialized=!1,this.responsiveState=null,this.config=Object.assign(Object.assign({},e),{security:Object.assign({enableSanitization:!0,enableRateLimit:!0,enableBotDetection:!0},e.security)}),this.apiConfig=new re(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 Vi(this.apiConfig),this.compositionsApi=new Ni(this.apiConfig),this.securityManager=Sr.getInstance(this.config.security||{}),this.displayManager=new xr,this.performanceMonitor=rr(),this.setupResponsiveTracking(),this.setupEventListeners(),te.info("[WidgetManager] Initialized with config:",{securityEnabled:!!(null===(t=e.security)||void 0===t?void 0:t.enableSanitization),performanceEnabled:!!(null===(i=e.performance)||void 0===i?void 0:i.enabled)})}static getInstance(e){return Nr.instance||(Nr.instance=new Nr(e)),Nr.instance}initialize(){return t(this,void 0,void 0,(function*(){if(this.isInitialized)te.warn("[WidgetManager] Already initialized");else try{this.setupResponsiveTracking(),this.isInitialized=!0,this.emitEvent({type:"manager_initialized",widgetId:"system",timestamp:Date.now()}),te.info("[WidgetManager] Successfully initialized")}catch(e){throw te.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 $r({widgetId:e,element:n,config:i.triggers});this.triggerManagers.set(e,t),te.debug("[WidgetManager] Trigger manager setup completed:",{widgetId:e,triggers:i.triggers})}catch(t){te.warn("[WidgetManager] Failed to setup trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}return i.compositionId&&this.trackWidgetForComposition(i.compositionId,e),this.widgets.set(e,o),this.widgetConfigs.set(e,i),o.state.ready=!0,te.info("[WidgetManager] Widget registered:",{widgetId:e,compositionId:i.compositionId}),this.emitEvent({type:"widget_registered",widgetId:e,data:{config:i},timestamp:Date.now()}),o}catch(t){throw te.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}}))}trackWidgetForComposition(e,t){this.compositionWidgets.has(e)||this.compositionWidgets.set(e,new Set),this.compositionWidgets.get(e).add(t)}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},en.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},en.CLIENT_URL||"*")}else e.element.dispatchEvent(new CustomEvent("widgetic:data-update",{detail:i}));te.debug("[WidgetManager] Content applied to widget:",{widgetId:e.id,contentType:typeof i})}catch(e){throw te.error("[WidgetManager] Failed to apply content:",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{te.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:gr(s)}),a=this.getWidgetsByComposition(e),d=this.compositionData.get(e);let l=i;n.partial&&(null==d?void 0:d.content)&&(l=this.mergeContent(d.content,i));const c={id:e,widgetId:e,content:l,theme:(null==d?void 0:d.theme)||{},version:n.version||(null==d?void 0:d.version)||"1.0.0"};this.compositionData.set(e,c);const u=a.map((i=>t(this,void 0,void 0,(function*(){var t;try{yield this.applyContentToWidget(i,l);const o=null===(t=i.updateHandlers)||void 0===t?void 0:t.get("content");o&&(yield o(l)),i.lastUpdate=Date.now(),te.debug("[WidgetManager] Content applied to widget:",{widgetId:i.id,compositionId:e,source:n.source})}catch(e){throw te.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:l,source:n.source,version:n.version,partial:n.partial},timestamp:Date.now()}),te.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{te.debug("[WidgetManager] Getting widget content schema:",{widgetId:e});const t=yield this.widgetsApi.getWidgetContentSchema({id:e});return te.debug("[WidgetManager] Content schema retrieved:",{widgetId:e,schema:t}),t}catch(t){throw te.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{te.debug("[WidgetManager] Getting widget design schema:",{widgetId:e});const t=yield this.widgetsApi.getWidgetDesignSchema({id:e});return te.debug("[WidgetManager] Design schema retrieved:",{widgetId:e,schema:t}),t}catch(t){throw te.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{te.debug("[WidgetManager] Validating content:",{compositionId:e});const o=yield this.compositionsApi.validateCompositionContent({id:e,body:gr(i)});return te.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 te.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),te.info("[WidgetManager] Update handler registered:",{widgetId:e,updateType:t})}unregisterWidget(e){return t(this,void 0,void 0,(function*(){var t;const i=this.widgets.get(e);if(i)try{const n=i.config.compositionId;n&&this.compositionWidgets.has(n)&&(this.compositionWidgets.get(n).delete(e),0===this.compositionWidgets.get(n).size&&this.compositionWidgets.delete(n));try{this.displayManager.cleanup(e),te.debug("[WidgetManager] Display management cleaned up:",{widgetId:e})}catch(t){te.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),te.debug("[WidgetManager] Trigger manager cleaned up:",{widgetId:e})}catch(t){te.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),te.info("[WidgetManager] Widget unregistered:",{widgetId:e,compositionId:n,remainingWidgetsForComposition:(null===(t=this.compositionWidgets.get(n||""))||void 0===t?void 0:t.size)||0}),this.emitEvent({type:"widget_unregistered",widgetId:e,data:{compositionId:n},timestamp:Date.now()})}catch(t){te.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 te.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"===Ur().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,te.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){te.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){te.error("[WidgetManager] Event handler failed:",e)}}))}emitError(e){this.errorHandlers.forEach((t=>{try{t(e)}catch(e){te.error("[WidgetManager] Error handler failed:",e)}}))}setupEventListeners(){"undefined"!=typeof window&&document.addEventListener("visibilitychange",(()=>{const e=!document.hidden;this.emitEvent({type:"page_visibility_change",widgetId:"system",data:{visible:e},timestamp:Date.now()})}))}getTriggerManager(e){return this.triggerManagers.get(e)}getAllTriggerManagers(){return new Map(this.triggerManagers)}getStats(){return{widgets:this.widgets.size,compositions:this.compositionWidgets.size,triggerManagers:this.triggerManagers.size,responsiveState:this.responsiveState,isInitialized:this.isInitialized}}destroy(){return t(this,void 0,void 0,(function*(){te.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(),te.debug("[WidgetManager] Trigger manager destroyed:",{widgetId:e})}catch(t){te.warn("[WidgetManager] Failed to destroy trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}this.triggerManagers.clear();try{this.displayManager.cleanupAll(),te.debug("[WidgetManager] Display manager cleaned up")}catch(e){te.warn("[WidgetManager] Failed to cleanup display manager:",{error:e instanceof Error?e.message:"Unknown error"})}this.eventListeners.clear(),this.errorHandlers.clear(),this.compositionWidgets.clear(),this.compositionData.clear(),this.isInitialized=!1,this.responsiveState=null,Nr.instance=null,te.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 Fr(e){return Nr.getInstance(e)}Nr.instance=null;var Kr=Object.freeze({__proto__:null,WidgetManager:Nr,getWidgetManager:Fr});const Hr="widgetic_session_id",Vr=new Map;let Gr=null;function Xr(e){var t;try{const t=localStorage.getItem(e);if(null!==t)return t}catch(e){}return null!==(t=Vr.get(e))&&void 0!==t?t:null}function Yr(e,t){Vr.set(e,t);try{localStorage.setItem(e,t)}catch(t){ee.debug("localStorage is not available; keeping the A/B test state in memory",{key:e,error:t})}}function Jr(){const e=Xr(Hr);return e||(Gr||(Gr=function(){try{if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return`visitor_${crypto.randomUUID()}`}catch(e){}return`visitor_${Math.random().toString(36).slice(2,12)}_${Date.now().toString(36)}`}()),Yr(Hr,Gr),Gr)}function Qr(e,t){return function(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return t>>>0}(`${t}:${e}`)%1e4/100}class Zr extends Or{constructor(){super(),this.assignments=new Map,this.conversionSetups=new Map,this.trackedConversions=new Set,this.visitors=new Map;const e=new re({basePath:an()});this.abTestingApi=new qi(e),this.compositionsApi=new Ni(e),this.widgetManager=Nr.getInstance(),this.messenger=new $s,this.setupEventListeners()}static getInstance(){return Zr.instance||(Zr.instance=new Zr),Zr.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 ee.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,goalTarget:e.goal_target||e.goalTarget||null}}catch(t){return ee.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 ee.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:n.primary_metric||(null===(i=n.success_metrics)||void 0===i?void 0:i[0])||"impressions"};return ee.info("A/B test config loaded",{experimentId:e,config:s}),s}catch(t){return t&&"object"==typeof t&&"status"in t&&404===t.status?(ee.warn("A/B test not found",{experimentId:e}),null):(ee.error("Failed to load A/B test config",{experimentId:e,error:t}),null)}}))}resolveVisitor(e){return{userId:(null==e?void 0:e.userId)||void 0,sessionId:(null==e?void 0:e.sessionId)||Jr()}}visitorFor(e,t){var i;return(null==t?void 0:t.userId)||(null==t?void 0:t.sessionId)?this.resolveVisitor(t):null!==(i=this.visitors.get(e))&&void 0!==i?i:this.resolveVisitor()}readStoredAssignment(e,t){try{const i=Xr(`ab_test_${e}`);if(!i)return null;const n=JSON.parse(i),o=t.variants.find((e=>e.id===n.variantId));return o?{variantId:o.id,compositionId:o.compositionId,embedCode:o.embedCode,goalTarget:o.goalTarget,recorded:!0===n.recorded}:(ee.info("Stored A/B test assignment is no longer a version of the test; assigning again",{experimentId:e}),null)}catch(t){return ee.warn("Stored A/B test assignment is unreadable; assigning again",{experimentId:e,error:t}),null}}storeAssignment(e,t){Yr(`ab_test_${e}`,JSON.stringify(t)),this.assignments.set(e,t)}getVariantAssignment(e,i){return t(this,void 0,void 0,(function*(){try{const t=yield this.getTestConfig(e);if(!t)return null;const n=this.resolveVisitor(i);if(this.visitors.set(e,n),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,goalTarget:i.goalTarget};return this.storeAssignment(e,t),t}}let o=this.readStoredAssignment(e,t);if(!o){const i=this.selectVariant(e,t.variants,n);if(!i)return null;o={variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode,goalTarget:i.goalTarget,recorded:!1},this.storeAssignment(e,o)}if(!o.recorded){(yield this.createAssignment(e,o,n))&&(o=Object.assign(Object.assign({},o),{recorded:!0}),this.storeAssignment(e,o))}return this.assignments.set(e,o),yield this.setupConversionTracking(e,t,o),o}catch(t){return ee.error("Failed to get variant assignment",{experimentId:e,error:t}),null}}))}setupConversionTracking(e,i,n){return t(this,void 0,void 0,(function*(){var t,o,s;try{const r=[i.primaryMetric],a=yield this.findTrackingTargets(n.compositionId,r),d={experimentId:e,variantId:n.variantId,metrics:r,trackingTargets:a,primaryMetric:i.primaryMetric,goalTarget:null!==(t=n.goalTarget)&&void 0!==t?t:null,widgetReportsGoals:null!==(s=null===(o=this.conversionSetups.get(e))||void 0===o?void 0:o.widgetReportsGoals)&&void 0!==s&&s};this.conversionSetups.set(e,d),ee.debug("Conversion tracking setup complete",{experimentId:e,trackedMetrics:r,trackingTargets:a})}catch(t){ee.error("Failed to setup conversion tracking",{experimentId:e,error:t})}}))}getPrimaryMetric(e){var t,i;return null!==(i=null===(t=this.conversionSetups.get(e))||void 0===t?void 0:t.primaryMetric)&&void 0!==i?i:null}setWidgetReportsGoals(e,t){const i=this.conversionSetups.get(e);i&&(i.widgetReportsGoals=t,ee.debug("Widget goal reporting capability set",{experimentId:e,widgetReportsGoals: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 ee.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)),ee.debug("Widget conversion tracking setup",{widgetId:e,experimentId:t})}catch(i){ee.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))}))}conversionKeyFor(e,t){return`ab_converted_${e}_${t.userId||t.sessionId}`}trackConversion(e,i,n,o,s){return t(this,void 0,void 0,(function*(){const t=this.conversionSetups.get(e),r=this.visitorFor(e,s),a=this.conversionKeyFor(e,r);let d=!1;try{if(!t)return void ee.warn("Conversion ignored: the test has no assignment in this page yet",{experimentId:e,conversionType:n});if(n!==t.primaryMetric)return void ee.debug("Conversion ignored: not the goal this test measures",{experimentId:e,conversionType:n,primaryMetric:t.primaryMetric});const s=null==o?void 0:o.goalTarget;if(t.goalTarget&&t.widgetReportsGoals&&s!==t.goalTarget)return void ee.debug("Conversion ignored: not the element this version measures",{experimentId:e,goalTarget:t.goalTarget,reportedGoalTarget:s});if(this.trackedConversions.has(a)||"1"===Xr(a))return ee.debug("Conversion already tracked for this visitor",{experimentId:e,variantId:i,conversionType:n}),void this.trackedConversions.add(a);this.trackedConversions.add(a),d=!0;const l={event_type:"conversion",data:gr({experimentId:e,variantId:t.variantId||i,userId:r.userId,sessionId:r.sessionId,conversionType:n,goalTarget:t.goalTarget||void 0,timestamp:(new Date).toISOString()})};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:l}),Yr(a,"1"),this.emit("conversion",{experimentId:e,variantId:i,conversionType:n,data:o}),ee.info("Conversion tracked",{experimentId:e,variantId:i,conversionType:n,data:o})}catch(t){d&&this.trackedConversions.delete(a),ee.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=this.visitorFor(e,n),o={event_type:"impression",data:gr({experimentId:e,variantId:i,userId:t.userId,sessionId:t.sessionId,timestamp:(new Date).toISOString()})};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:o}),ee.debug("Impression tracked",{experimentId:e,variantId:i})}catch(t){ee.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 ee.info("Goal tracking validation completed",{variants:e.length,successMetrics:i,issues:t.length,isValid:o}),{isValid:o,issues:t,recommendations:n}}catch(e){return ee.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){ee.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){ee.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,i){return function(e,t,i){if(!e||0===e.length)return null;const n=Qr(t,i);let o=0;for(const t of e)if(o+=Number(t.trafficPercentage)||0,n<o)return t;return e[e.length-1]}(t,i.userId||i.sessionId,e)}createAssignment(e,i,n){return t(this,void 0,void 0,(function*(){try{const t="undefined"!=typeof navigator?navigator.userAgent:void 0,o=gr({experimentId:e,variantId:i.variantId,userId:n.userId,sessionId:n.sessionId,userAgent:t,deviceType:this.detectDeviceType(t)});return yield this.abTestingApi.createABTestAssignment({createABTestAssignmentRequest:o}),ee.debug("Assignment created in backend",{experimentId:e,variantId:i.variantId}),!0}catch(t){return ee.error("Failed to create assignment in backend",{experimentId:e,error:t}),!1}}))}generateEmbedCode(e){return`<widgetic-widget composition-id="${e}"></widgetic-widget>`}getSessionId(){return Jr()}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"}}Zr.instance=null;var ea=Object.freeze({__proto__:null,ABTestManager:Zr});class ta{static analyzeElement(e){try{const t=this.getExplicitMetadata(e);return t||this.analyzeHeuristically(e)}catch(e){return null}}static getExplicitMetadata(e){const t=e.getAttribute("data-widget-meta");if(t)try{return JSON.parse(t)}catch(e){}const i=e.getAttribute("data-capabilities");if(i)return this.parseCapabilitiesString(i);const n=e.querySelector('script[type="application/json"]');if(n&&n.textContent)try{const e=JSON.parse(n.textContent);return e.capabilities||e.metadata}catch(e){}return null}static analyzeHeuristically(e){const t={type:"custom",version:"1.0.0"},i=e.getAttribute("data-widget-type")||e.getAttribute("data-type")||this.inferTypeFromStructure(e);switch(i&&(t.type=i),t.type){case"media":t.mediaCapabilities=this.analyzeMediaCapabilities(e);break;case"gallery":t.contentCapabilities=this.analyzeContentCapabilities(e);break;case"form":t.textCapabilities=this.analyzeTextCapabilities(e);break;case"interactive":t.interactionCapabilities=this.analyzeInteractionCapabilities(e)}return t.supportsResponsive=this.checkResponsiveSupport(e),t.supportsAutoscale=this.checkAutoscaleSupport(e),t.supportsThemes=this.checkThemeSupport(e),t.displayCapabilities=this.analyzeDisplayCapabilities(e),t.abTestingCapabilities=this.analyzeABTestingCapabilities(e),t}static inferTypeFromStructure(e){var t;return e.querySelector("video, audio")||e.classList.contains("media-widget")||(null===(t=e.getAttribute("data-widget-id"))||void 0===t?void 0:t.includes("video"))?"media":e.querySelector("form, input, textarea")||e.classList.contains("form-widget")?"form":e.querySelector(".gallery, .carousel")||e.classList.contains("gallery-widget")||e.querySelectorAll("img").length>1?"gallery":e.querySelector("button, .interactive")||e.classList.contains("quiz-widget")||e.classList.contains("poll-widget")?"interactive":"custom"}static analyzeMediaCapabilities(e){const t=e.querySelectorAll("video"),i=e.querySelectorAll("audio"),n=null!==e.querySelector("[controls]"),o=null!==e.querySelector("[data-volume], .volume-control");let s="audio";return t.length>0&&i.length>0?s="mixed":t.length>0&&(s="video"),{supportsPlay:!0,supportsPause:!0,supportsVolumeControl:o||n,supportsSeek:n,supportsGlobalVolume:e.hasAttribute("data-global-volume"),mediaType:s}}static analyzeContentCapabilities(e){const t=e.querySelectorAll(".item, .slide, img, .content-item"),i=null!==e.querySelector(".nav, .navigation, button"),n=e.hasAttribute("data-position")||e.hasAttribute("data-track-position");let o="gallery";return e.classList.contains("carousel")&&(o="carousel"),e.classList.contains("list")&&(o="list"),e.classList.contains("grid")&&(o="grid"),{supportsPositionTracking:n,supportsNavigation:i,contentType:o,totalItems:t.length}}static analyzeTextCapabilities(e){const t=e.querySelectorAll("input, textarea, select"),i=Array.from(t).map((e=>e.getAttribute("name")||e.getAttribute("id")||"unknown"));return{supportsTextPersistence:e.hasAttribute("data-persist")||e.hasAttribute("data-autosave"),supportsSanitization:!0,fields:i}}static analyzeInteractionCapabilities(e){const t=e.querySelectorAll("button").length>0,i=e.querySelectorAll("form").length>0,n=e.hasAttribute("data-events")||e.hasAttribute("data-track-interactions"),o=[],s=e.getAttribute("data-events");return s&&o.push(...s.split(",").map((e=>e.trim()))),{supportsClicks:t||null!==e.querySelector("[onclick]"),supportsFormSubmission:i,supportsCustomEvents:n,customEventTypes:o.length>0?o:void 0}}static analyzeDisplayCapabilities(e){return{supportsFullscreen:e.hasAttribute("data-fullscreen")||e.classList.contains("fullscreen-capable"),supportsOverlay:e.hasAttribute("data-overlay")||e.classList.contains("overlay-capable"),supportsPopup:e.hasAttribute("data-popup")||e.classList.contains("popup-capable"),supportsInline:!0}}static analyzeABTestingCapabilities(e){if(!("widgetic-abtest"===e.tagName.toLowerCase()||e.hasAttribute("experiment-id")||e.hasAttribute("data-ab-test")))return;const t=[],i=[];return e.querySelector("button, a, [onclick]")&&(t.push("clicks"),i.push("clicks")),e.querySelector("form")&&(t.push("submissions"),i.push("conversions")),e.querySelector("video, audio")&&(t.push("plays"),i.push("plays")),t.push("impressions"),{supportsTracking:!0,trackableEvents:t,conversionGoals:i}}static checkResponsiveSupport(e){return e.hasAttribute("data-responsive")||e.hasAttribute("data-breakpoints")||e.classList.contains("responsive")}static checkAutoscaleSupport(e){return e.hasAttribute("data-autoscale")||e.hasAttribute("data-auto-height")||e.classList.contains("autoscale")}static checkThemeSupport(e){return e.hasAttribute("data-theme")||e.classList.contains("themeable")||null!==e.querySelector("[data-theme]")}static parseCapabilitiesString(e){const t=e.split(",").map((e=>e.trim()));return{type:"custom",version:"1.0.0",mediaCapabilities:t.includes("media")?{supportsPlay:!0,supportsPause:!0,supportsVolumeControl:t.includes("volume"),supportsSeek:t.includes("seek"),supportsGlobalVolume:t.includes("global-volume"),mediaType:"mixed"}:void 0,textCapabilities:t.includes("forms")?{supportsTextPersistence:t.includes("persist"),supportsSanitization:!0,fields:[]}:void 0,interactionCapabilities:t.includes("interactive")?{supportsClicks:!0,supportsFormSubmission:t.includes("forms"),supportsCustomEvents:t.includes("events")}:void 0,supportsResponsive:t.includes("responsive"),supportsAutoscale:t.includes("autoscale"),supportsThemes:t.includes("themes")}}}function ia(e){var t,i,n,o;const s=new Set;return s.add("rendering"),s.add("api"),e.mediaCapabilities&&s.add("media"),e.textCapabilities&&s.add("security"),e.interactionCapabilities&&s.add("messaging"),((null===(t=e.displayCapabilities)||void 0===t?void 0:t.supportsFullscreen)||(null===(i=e.displayCapabilities)||void 0===i?void 0:i.supportsOverlay)||(null===(n=e.displayCapabilities)||void 0===n?void 0:n.supportsPopup))&&s.add("display"),e.abTestingCapabilities&&(s.add("abTesting"),s.add("messaging")),(null===(o=e.performanceRequirements)||void 0===o?void 0:o.requiresLazyLoading)&&s.add("performance"),Array.from(s)}var na=Object.freeze({__proto__:null,WidgetMetadataAnalyzer:ta,analyzeWidgetRequirementsEnhanced:function(e){const t=new Set;for(const i of e){const e=ta.analyzeElement(i);if(e){ia(e).forEach((e=>t.add(e)))}}return Array.from(t)},getRequiredChunks:ia});const oa="data-widgetic-overlay",sa="data-device-restricted",ra=new WeakMap,aa=new WeakMap,da=new Map;function la(e,t,i){if(ra.has(e))return;const n=e.getAttribute("composition-id")||"widget",o=function(e,t){const i=aa.get(e);if(i)return i;const n=(da.get(t)||0)+1;da.set(t,n);const o=1===n?t:`${t}-${n}`;return aa.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 Br})).then((({TriggerManager:i})=>{if(ra.has(e))return void s();const n=new i({widgetId:o,element:e,config:t,displayWhenShown:"block"});ra.set(e,n),e.hasAttribute(oa)&&e.setAttribute(oa,"armed"),te.debug("[published-host-display] Trigger manager armed",{widgetId:o,mode:t.mode,eventTrigger:t.eventTrigger})})).catch((e=>{s(),te.error("[published-host-display] Could not load the overlay triggers; the embed stays hidden",{widgetId:o,error:e})}))}const ca=/^[A-Za-z0-9_.-]{1,64}$/;function ua(e){return(new TextEncoder).encode(JSON.stringify(e)).length}function ha(e){if(!e||!e.trim())return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch(e){return null}}function ga(e){const t=ha(e);if(!t)return null;const i=Object.keys(t);if(i.length>50)return null;if(ua(t)>8192)return null;const n={};for(const e of i){if(!ca.test(e))return null;const i=t[e];if("boolean"==typeof i)n[e]=i;else if("number"==typeof i){if(!Number.isFinite(i))return null;n[e]=i}else{if("string"!=typeof i)return null;if(i.length>2e3)return null;n[e]=i}}return n}function pa(e){if(!(null==e?void 0:e.trim()))return null;const t=e.trim();if(t.length>2048)return null;try{return"https:"!==new URL(t).protocol?null:t}catch(e){return null}}const ma=new WeakMap;function fa(e){var t;const i=e.getAttribute("context"),n=function(e){const t=ha(e);if((null==e?void 0:e.trim())&&!t)return{value:null,invalid:!0};if(!t)return{value:null,invalid:!1};const i=Object.keys(t);if(i.length>20)return{value:null,invalid:!0};if(ua(t)>2048)return{value:null,invalid:!0};const n={};for(const e of i){if(!ca.test(e))return{value:null,invalid:!0};const i=t[e];if("number"==typeof i){if(!Number.isFinite(i))return{value:null,invalid:!0};n[e]=i}else{if("string"!=typeof i)return{value:null,invalid:!0};if(i.length>500)return{value:null,invalid:!0};n[e]=i}}return{value:n,invalid:!1}}(i);return n.invalid&&function(e,t){const i=null!=t?t:"";let n=ma.get(e);n||(n=new Set,ma.set(e,n)),n.has(i)||n.add(i)}(e,i),{context:n.invalid?null:n.value,contextInvalid:n.invalid,values:ga(e.getAttribute("values")),mediaResolver:pa(null!==(t=e.getAttribute("media-resolver"))&&void 0!==t?t:e.getAttribute("mediaresolver"))}}const va="data-widgetic-context-invalid";const ya=new WeakMap;function wa(e){const t=ya.get(e);if(t){ya.delete(e);try{t.instance.destroy()}catch(e){}t.stop()}for(const t of Array.from(e.querySelectorAll("[data-widgetic-direct]")))t.remove()}function ba(e,t){const i=fa(e);i.contextInvalid?e.setAttribute(va,""):e.removeAttribute(va);const n=Ts(e,t),o=Object.assign(Object.assign(Object.assign({},t.content||{}),n.content),i.values||{}),s=Object.assign(Object.assign({},t.design||{}),n.design),r=n.contentItems&&n.contentItems.length>0?n.contentItems:t.contentItems||[];return Object.assign({design:s,content:o,contentItems:r,context:i.context,mediaResolver:i.mediaResolver},t.entries?{entries:t.entries}:{})}function Ia(e,i,n,o){return t(this,void 0,void 0,(function*(){as(e);const t=ds(e)||"",s=i.direct;if(!s||2!==s.contractVersion||!s.moduleUrl)return!1;let r;try{r=yield(a=s.moduleUrl,import(a))}catch(e){return!1}var a;if(!e.isConnected||(ds(e)||"")!==t)return!1;if(2!==r.contractVersion)return!1;wa(e);const d=document.createElement("div");d.setAttribute("data-widgetic-direct","1"),d.setAttribute("width",n||e.getAttribute("width")||"400");const l=e.getAttribute("height");l&&d.setAttribute("height",l);const c=d.attachShadow({mode:"open"}),u=document.createElement("style");u.textContent=r.getStyles();const h=document.createElement("div");h.className="widgetic-direct-target",c.append(u,h);const g={compositionId:t,payload:i,instance:null,stop:()=>{}},p=r.mount(h,ba(e,g.payload));g.instance=p;const m=function(e,t,i){const n="undefined"!=typeof MutationObserver?MutationObserver:null;if(!n)return()=>{};let o;try{o=new n((n=>{Ss(n)&&i.update(ba(e,t()))}))}catch(e){return()=>{}}return o.observe(e,{attributes:!0,childList:!0,subtree:!0,characterData:!0}),()=>o.disconnect()}(e,(()=>g.payload),p),f=["play","pause","ended","seeking","seeked","timeupdate","progress","volumechange","trackchange","playlistchange"],v=["position","navigate","complete","reset","metadata"],y=[];let w=!1,b=0;for(const i of f){const n=`widgetic:media:${i}`,o=e=>{if(w)return;const n=e,o=n.detail&&"object"==typeof n.detail?n.detail:{};try{Ws().handleMediaEvent({type:i,compositionId:t,config:{persistState:!0,autoResume:!0},data:o})}catch(e){}};h.addEventListener(n,o),e.addEventListener(n,o),y.push((()=>{h.removeEventListener(n,o),e.removeEventListener(n,o)}))}const I=["play","pause","timeupdate","seeking","volumechange","ended"];for(const e of I){const i=i=>{if(w)return;const n=i.target;if(!n||"AUDIO"!==n.tagName&&"VIDEO"!==n.tagName)return;if("pause"===e&&n.ended)return;if("timeupdate"===e){const e=Date.now();if(e-b<750)return;b=e}const o="VIDEO"===n.tagName?"video":"audio";try{Ws().handleMediaEvent({type:e,compositionId:t,config:{mediaType:o,persistState:!0,autoResume:!0},data:{mediaType:o,position:n.currentTime||0,duration:Number.isFinite(n.duration)?n.duration:void 0,volume:n.muted?0:n.volume,playing:!n.paused}})}catch(e){}};h.addEventListener(e,i,!0),y.push((()=>{h.removeEventListener(e,i,!0)}))}const T=e=>{const t=e.detail;if(!t||"object"!=typeof t)return;const i=Array.from(h.querySelectorAll("audio, video")),n=i.find((e=>!e.paused))||i[0]||null;w=!0;try{if("pause"===t.command)for(const e of i){if("number"==typeof t.position&&!Number.isNaN(t.position)&&t.position>=0)try{e.currentTime=t.position}catch(e){}try{e.pause()}catch(e){}}else if("play"===t.command){if(n){if("number"==typeof t.position&&!Number.isNaN(t.position)&&t.position>=0)try{n.currentTime=t.position}catch(e){}try{const e=n.play();e&&"function"==typeof e.catch&&e.catch((()=>{}))}catch(e){}}}else if("restore"===t.command&&t.state){if(n&&("number"==typeof t.state.volume&&(n.volume=Math.max(0,Math.min(1,t.state.volume))),"number"==typeof t.state.position&&!Number.isNaN(t.state.position)&&t.state.position>=0))try{n.currentTime=t.state.position}catch(e){}}else if("setVolume"===t.command&&"number"==typeof t.volume){const e=Math.max(0,Math.min(1,t.volume));for(const t of i)t.volume=e}}finally{setTimeout((()=>{w=!1}),150)}};h.addEventListener("widgetic:media:command",T),y.push((()=>{h.removeEventListener("widgetic:media:command",T)}));for(const i of v){const n=`widgetic:content:${i}`,o=e=>{const n=e,o=n.detail&&"object"==typeof n.detail?n.detail:{};try{Us().handleContentPositionEvent({type:i,compositionId:t,config:{contentType:"custom",persistState:!0,autoResume:!0},data:o})}catch(e){}};h.addEventListener(n,o),e.addEventListener(n,o),y.push((()=>{h.removeEventListener(n,o),e.removeEventListener(n,o)}))}g.stop=()=>{m();for(const e of y)e()},ya.set(e,g),e.appendChild(d),o(e);try{Us().resumeWidgetPosition(t)}catch(e){}try{Ws().resumeWidget(t)}catch(e){}return e.dispatchEvent(new CustomEvent("widgetic:ready",{bubbles:!0,composed:!0,detail:{compositionId:t}})),!0}))}const Ta="data-widgetic-refused",ka="data-widgetic-context-invalid",Sa="data-widgetic-composition-tracked";function Ca(e,t){const i=e.getAttribute(Sa);if(i&&i!==t){!function(e){e.removeAttribute("data-widgetic-mounting"),e.removeAttribute("data-widgetic-mounted"),e.removeAttribute(sa),e.removeAttribute(Ta),e.removeAttribute(ka)}(e),wa(e);for(const t of Array.from(e.querySelectorAll("iframe")))t.remove();e.style.display="",e.removeAttribute("data-widgetic-overlay")}e.setAttribute(Sa,t)}const Aa=["context","values","media-resolver"],Ea=new Set(["widgetic:ready","widgetic:error","widgetic:submitted","widgetic:resize","widgetic:data","widgetic:interaction","widgetic:form-submit","widgetic:goal"]);const Ra=new WeakMap;class xa{constructor(e,t,i,n){this.host=e,this.iframe=t,this.gatewayOrigin=i,this.compositionId=n,this.readyDispatched=!1,this.latestAbGoal=null,this.attributeFlushScheduled=!1,this.attributeObserver=null,as(this.host),this.onWindowMessage=e=>this.handleWrapperMessage(e),window.addEventListener("message",this.onWindowMessage),this.iframe.addEventListener("load",(()=>this.postHostSnapshot())),this.observeHostAttributes()}observeHostAttributes(){const e="undefined"!=typeof MutationObserver?MutationObserver:null;if(!e)return;let t;try{t=new e((e=>{e.some((e=>"attributes"===e.type&&e.attributeName&&Aa.includes(e.attributeName)))&&this.scheduleHostSnapshot()}))}catch(e){return}t.observe(this.host,{attributes:!0,attributeFilter:[...Aa]}),this.attributeObserver=t}scheduleHostSnapshot(){this.attributeFlushScheduled||(this.attributeFlushScheduled=!0,queueMicrotask((()=>{this.attributeFlushScheduled=!1,this.postHostSnapshot()})))}postHostSnapshot(){try{const e=fa(this.host);e.contextInvalid?this.host.setAttribute(ka,"1"):this.host.removeAttribute(ka);const t=this.iframe.contentWindow;if(!t)return;const i=function(e,t){return{type:"widgetic:host",version:1,compositionId:e,context:t.context,values:t.values,mediaResolver:t.mediaResolver}}(this.compositionId,e);t.postMessage(i,this.gatewayOrigin),this.postAbGoal()}catch(e){}}sendAbGoal(e){this.latestAbGoal=e,this.postAbGoal()}postAbGoal(){if(this.latestAbGoal)try{const e=this.iframe.contentWindow;if(!e)return;e.postMessage({type:"widgetic:ab-goal",compositionId:this.compositionId,metric:this.latestAbGoal.metric,goalTarget:this.latestAbGoal.goalTarget},this.gatewayOrigin)}catch(e){}}sendWidgetUpdate(e){try{const t=this.iframe.contentWindow;if(!t)return;t.postMessage(Object.assign(Object.assign(Object.assign({type:"widgetic:update",compositionId:this.compositionId},e.design?{design:e.design}:{}),e.content?{content:e.content}:{}),e.contentItems?{contentItems:e.contentItems}:{}),this.gatewayOrigin)}catch(e){}}handleWrapperMessage(e){var t,i;if(e.source!==this.iframe.contentWindow)return;if(e.origin!==this.gatewayOrigin)return;const n=e.data;if(!n||"object"!=typeof n||Array.isArray(n))return;const o=n.type;if("string"!=typeof o)return;const s=n.compositionId;if("string"==typeof s&&s!==this.compositionId)return;let r=null!==(i=null!==(t=n.detail)&&void 0!==t?t:n.payload)&&void 0!==i?i:n.data;if(void 0===r){const e={};for(const t of Object.keys(n))"type"!==t&&"compositionId"!==t&&(e[t]=n[t]);Object.keys(e).length>0&&(r=e)}const a=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};try{const t=JSON.stringify(e);return(new TextEncoder).encode(t).length>8192?{}:e}catch(e){return{}}}(r),d=Object.assign({compositionId:this.compositionId},a);if(o.startsWith("widgetic:media:")){const e=o.replace("widgetic:media:","");try{Ws().handleMediaEvent({type:e,compositionId:this.compositionId,config:{persistState:!0,autoResume:!0},data:a})}catch(e){}this.dispatchHostEvent(o,d)}else if(o.startsWith("widgetic:content:")){const e=o.replace("widgetic:content:","");try{Us().handleContentPositionEvent({type:e,compositionId:this.compositionId,config:{contentType:"custom",persistState:!0,autoResume:!0},data:a})}catch(e){}this.dispatchHostEvent(o,d)}else if(Ea.has(o))if("widgetic:ready"!==o)this.dispatchHostEvent(o,d);else{try{Us().resumeWidgetPosition(this.compositionId)}catch(e){}try{Ws().resumeWidget(this.compositionId)}catch(e){}if(this.readyDispatched)return;this.readyDispatched=!0,this.postHostSnapshot();const e=function(e){const t=e.capabilities;return Array.isArray(t)?t.filter((e=>"string"==typeof e&&e.length<=40)).slice(0,32):[]}(a);this.dispatchHostEvent("widgetic:ready",Object.assign({compositionId:this.compositionId},e.length>0?{capabilities:e}:{}))}}dispatchHostEvent(e,t){this.host.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}destroy(){var e;window.removeEventListener("message",this.onWindowMessage),null===(e=this.attributeObserver)||void 0===e||e.disconnect(),this.attributeObserver=null}}function Ma(e,t,i){e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{compositionId:t,code:i},bubbles:!0,composed:!0}))}function Wa(e){e.setAttribute("data-widgetic-mounted","1"),e.removeAttribute("data-widgetic-mounting"),e.hasAttribute(oa)||(e.style.display="block")}function Da(e,t,i,n){Wa(e);const o=ds(e),s=ks(e,i),r=es(t,n||e.getAttribute("width")||"400",e.getAttribute("height")||"300",o||void 0,s);if(e.appendChild(r),o)try{!function(e,t,i,n){let o;try{o=new URL(i).origin}catch(e){return}const s=Ra.get(e);s&&s.destroy();const r=new xa(e,t,o,n);Ra.set(e,r),r.postHostSnapshot()}(e,r,t,o)}catch(e){}try{!function(e,t,i){const n=Cs.get(e);n&&n();const o="undefined"!=typeof MutationObserver?MutationObserver:null;if(!o)return()=>{};let s,r=!1;try{s=new o((n=>{Ss(n)&&(r||(r=!0,queueMicrotask((()=>{r=!1;const n=Ts(e,t);i(n)}))))}))}catch(e){return()=>{}}s.observe(e,{attributes:!0,childList:!0,subtree:!0,characterData:!0});const a=()=>{s.disconnect(),Cs.delete(e)};Cs.set(e,a)}(e,i,(t=>{const i=function(e){return Ra.get(e)}(e);if(i)i.sendWidgetUpdate({design:t.design,content:t.content,contentItems:t.contentItems});else if(r.contentWindow)try{r.contentWindow.postMessage(Object.assign(Object.assign(Object.assign({type:"widgetic:update"},t.design?{design:t.design}:{}),t.content?{content:t.content}:{}),t.contentItems?{contentItems:t.contentItems}:{}),"*")}catch(e){}}))}catch(e){}}function Oa(e,t,i){var n;const o=ds(e)||"",s=ks(e,t);("iframe"===e.getAttribute("render-mode")||"true"===e.getAttribute("use-iframe")||!e.getAttribute("composition-id")&&Boolean(o)&&!(null===(n=s.direct)||void 0===n?void 0:n.moduleUrl))&&s.embedUrl?Da(e,s.embedUrl,s,i):Ia(e,s,i,Wa).then((t=>{t||e.isConnected&&(ds(e)||"")===o&&(e.getAttribute("data-widgetic-mounted")||La(e,o,"REPUBLISH_REQUIRED","republish_required"))}))}function La(e,t,i,n){e.removeAttribute("data-widgetic-mounting"),e.setAttribute(Ta,i),Ma(e,t,n)}function Ua(e){var t;as(e);const i=ss(e),n=null!==(t=null==i?void 0:i.id)&&void 0!==t?t:null;if(bs(e),n&&Ca(e,n),e.getAttribute("data-widgetic-mounted")||e.getAttribute("data-widgetic-mounting")||e.getAttribute(sa)||e.getAttribute(Ta))return!0;const o=e.getAttribute("src");if(o)return Da(e,o),!0;if(!i||!n)return!1;const s=e.hasAttribute(sa),r=function(e){var t,i,n,o,s;let r;try{r=Cn(e)}catch(e){return te.warn("[published-host-display] Could not read the embed's display settings",{error:e}),{suppressed:!1}}return Pr(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(oa,"pending")),{suppressed:!1,triggers:r.triggers}):(e.style.display="none",e.setAttribute(sa,"true"),te.debug("[published-host-display] Embed skipped: this device is switched off",{compositionId:r.compositionId,device:r.device}),{suppressed:!0})}(e);if(r.suppressed)return s||Ma(e,n,"device_restricted"),!0;e.setAttribute("data-widgetic-mounting","1");return("widget"===i.kind?Jo(n):Yo(n)).then((t=>{var i;if(e.getAttribute("data-widgetic-mounted"))return;if("refused"===t.status)return e.removeAttribute("data-widgetic-mounting"),e.setAttribute(Ta,t.refusal.code),Zo(n,t.refusal),void Ma(e,n,Io(t.refusal.code)||"domain_not_allowed");if("failed"===t.status)return void La(e,n,t.failure.gatewayCode,t.failure.stateCode);const o="found"===t.status?t.payload:null;if(!(null==o?void 0:o.embedUrl))return e.removeAttribute("data-widgetic-mounting"),void La(e,n,"NOT_FOUND","not_found");const{triggers:s}=r;if("overlay"!==(null==s?void 0:s.mode))Oa(e,o),s&&la(e,s);else{const t=(null===(i=s.overlay)||void 0===i?void 0:i.fullWidth)?"100%":void 0;la(e,s,(()=>Oa(e,o,t)))}})),!0}function Pa(e=document){const t=e.querySelectorAll("widgetic, widgetic-embed");let i=0;for(const e of Array.from(t))e instanceof HTMLElement&&Ua(e)&&(i+=1);return i}const _a={mobile:480,tablet:768,desktop:1024},za={MANUAL:"manual",EXIT_INTENT:"exit-intent",ON_SCROLL:"on-scroll",TIME_DELAY:"time-delay",ENGAGEMENT_THRESHOLD:"engagement",EXTERNAL_TRIGGER:"external"},qa={DEFAULT_ANIMATION:"fade",DEFAULT_DELAY_MS:1e3,SUPPORTED_ANIMATIONS:["fade","slide-up","slide-down","slide-left","slide-right","zoom","bounce"]};class ja{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:_a.mobile,tablet:_a.tablet,desktop:_a.desktop}),this.isEnabled=this.config.enabled,this.isEnabled&&this.initializeEventListeners(),te.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&&(te.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)),te.info("Overlay displayed",{displayMode:t.displayMode,animation:t.animation,autoClose:t.autoClose}),this.emitOverlayEvent("overlay-shown",t)}catch(t){te.error("Failed to show overlay",{error:t,config:e})}}else te.warn("Overlay manager is disabled")}validateOverlayConfig(e){const t=Object.assign({},e);return t.displayMode&&Object.values(za).includes(t.displayMode)||(t.displayMode=za.MANUAL),t.animation&&qa.SUPPORTED_ANIMATIONS.includes(t.animation)||(t.animation=qa.DEFAULT_ANIMATION,te.debug("Using default animation for overlay",{provided:e.animation,defaultUsed:qa.DEFAULT_ANIMATION})),t.delay||(t.delay=qa.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,te.debug("Overlay hidden"),this.emitOverlayEvent("overlay-hidden",{})}createOverlayElement(e){const t=document.createElement("div");t.className=`widgetic-overlay widgetic-overlay-${e.animation||qa.DEFAULT_ANIMATION}`,!1!==e.showBackdrop&&t.classList.add("widgetic-overlay-backdrop"),t.innerHTML=`\n <div class="widgetic-overlay-content">\n <button class="widgetic-overlay-close">×</button>\n <div class="widgetic-overlay-body">\n ${e.content}\n </div>\n </div>\n `,this.addOverlayStyles();const i=t.querySelector(".widgetic-overlay-close");i&&(i.setAttribute("aria-label",js("close")),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||_a.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||_a.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:qa.DEFAULT_ANIMATION,delay:qa.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,te.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),te.debug("OverlayManager destroyed")}}let $a=null;class Ba{constructor(e={}){this.items=new Map,this.observer=null,this.preloadObserver=null,this.loadingQueue=[],this.activeLoads=0,this.performanceMonitor=rr(),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)),l=e.length>0?d.length/e.length:0;return{totalItems:e.length,loadedItems:t.length,failedItems:i.length,averageLoadTime:o,viewportUtilization:a,preloadSuccess:l}}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 Na=null;class Fa{constructor(e={}){this.resources=new Map,this.loadQueue=[],this.activeRequests=0,this.performanceMonitor=rr(),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 Ka=null;function Ha(e){return Ka||(Ka=new Fa(e)),Ka}let Va=!1;class Ga{constructor(e={}){var t,i,n,o,s,r,a,d,l,c,u,h,g,p,m,f,v,y,w,b,I,T;this.version=Yi,this.instances=new Map,this.isInitialized=!1,this.renderer=tr(),this.widgetControllers=new Map,this.authDetector=fr(),this.editorOverlay=Tr(),this.displayManager=Wr(),this.resizeHandler=(Hs||(Hs=new Ks(T)),Hs),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=to(),this.messenger=Ns(this.config.messagingOptions);const k=this.config.logLevel||(this.config.debug?"debug":"info");if(te.setLevel(k),hn.enabled&&te.info("Initializing EmbedSDK",{version:Yi,config:this.config,browserCapabilities:this.browserCapabilities}),"updateConfig"in this.displayManager&&"function"==typeof this.displayManager.updateConfig&&this.displayManager.updateConfig(this.config.displayOptions||{}),"updateConfig"in this.resizeHandler&&"function"==typeof this.resizeHandler.updateConfig&&this.resizeHandler.updateConfig(this.config.resizeOptions||{}),!1!==(null===(t=this.config.performance)||void 0===t?void 0:t.enabled)){ar(Object.assign({enableTracking:gn.ENABLE_PERFORMANCE_TRACKING,axiomApiKey:gn.AXIOM_API_KEY,axiomDataset:gn.AXIOM_DATASET,axiomApiEndpoint:gn.AXIOM_API_ENDPOINT,statsigKey:gn.STATSIG_API_KEY,statsigApiEndpoint:gn.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={}){Na=new Ba(e)}((null===(o=this.config.lazyLoading)||void 0===o?void 0:o.config)||{}),void 0!==this.config.debug&&(ee.setDebug(this.config.debug),this.config.debug&&ee.setLevel("debug")),!1!==(null===(s=this.config.resourceOptimization)||void 0===s?void 0:s.enabled)&&function(e={}){Ka=new Fa(e)}((null===(r=this.config.resourceOptimization)||void 0===r?void 0:r.config)||{}),this.config.editorOptions&&(this.editorOverlay=Tr(this.config.editorOptions)),!1!==(null===(a=this.config.overlayConfig)||void 0===a?void 0:a.enabled)&&(this.overlayManager=function(e){return $a||($a=new ja(e)),$a}({enabled:!0,defaultMode:null===(d=this.config.overlayConfig)||void 0===d?void 0:d.defaultMode,exitIntentEnabled:null===(l=this.config.overlayConfig)||void 0===l?void 0:l.exitIntentEnabled,scrollTriggerEnabled:null===(c=this.config.overlayConfig)||void 0===c?void 0:c.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}})),te.info("Widgetic Embed SDK v1.0 initialized",{version:Yi,capabilities:this.browserCapabilities,editingEnabled:!1!==this.config.enableEditing,overlayEnabled:null!==this.overlayManager}),this.config.debug&&te.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)te.warn("SDK already initialized");else if(Va||"undefined"!=typeof window&&window.__WIDGETIC_SDK_INITIALIZED__)te.warn("SDK initialization detected, skipping duplicate setup");else try{if(this.isInitialized=!0,Va=!0,"undefined"!=typeof window&&(window.__WIDGETIC_SDK_INITIALIZED__=!0),!1!==this.config.enableEditing&&this.checkAuthentication().catch((e=>{te.warn("Background authentication check failed",{error:e})})),this.config.preloadUISDK&&(null===(e=this.authenticationStatus)||void 0===e?void 0:e.isAuthenticated))try{const e=wr();yield e.preload(),te.info("UI SDK preloaded successfully")}catch(e){te.warn("Failed to preload UI SDK",{error:e})}yield this.scanPage(),te.info("Widgetic Embed SDK initialized successfully",{version:Yi,capabilities:this.browserCapabilities,authenticationStatus:null===(t=this.authenticationStatus)||void 0===t?void 0:t.isAuthenticated}),yield this.scanPage()}catch(e){throw te.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?te.info("User authenticated for editing",{userId:null===(e=this.authenticationStatus.user)||void 0===e?void 0:e.id}):te.debug("User not authenticated for editing")}catch(e){te.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*(){te.info("Refreshing widgets"),yield this.scanPage()}))}watchPublishedHosts(){Pa(),this.hostObserverStarted||"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.hostObserverStarted=!0,new MutationObserver((()=>{Pa()})).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(te.debug("Found widgetic host elements",{count:o.length}),0===o.length)return void te.info("No widgets found on page");const s=[];for(const r of Array.from(o))if(Hn(r)&&r instanceof HTMLElement){if(Ua(r))continue;try{const o=Cn(r),a=null===(t=null===(e=o.device)||void 0===e?void 0:e.mobileEnabled)||void 0===t||t;if(!Pr(a,null===(n=null===(i=o.device)||void 0===i?void 0:i.desktopEnabled)||void 0===n||n)){te.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){te.error("Failed to parse widget configuration",{element:r.outerHTML,error:e})}}0!==s.length?yield this.renderWidgetsBatch(s):te.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:so(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=Kn(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 l={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(l.id,l),yield this.maybeAddEditorOverlay(o.element,s.compositionId),te.debug("Widget rendered successfully",{instanceId:l.id,compositionId:s.compositionId,renderMode:o.renderMode,displayMode:s.displayMode})}te.info("Batch widget rendering complete",{rendered:n.length,total:e.length})}catch(t){te.error("Batch widget rendering failed",{error:t});for(const{element:t,config:i}of e)try{yield this.renderSingleWidget(t,i)}catch(e){te.error("Individual widget rendering failed",{compositionId:i.compositionId,error:e})}}}))}renderSingleWidget(e,i){return t(this,void 0,void 0,(function*(){try{performance.now(),rr(),Ha();const n=function(e){return Na||(Na=new Ba(e)),Na}();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=rr(),n=e instanceof Error?e.message:"Render failed";throw t.recordWidgetError(i.compositionId,n),t.endWidgetLoad(i.compositionId,!1),te.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=rr(),o=Ha();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=rr(),n=e instanceof Error?e.message:"Render failed";throw t.recordWidgetError(i.compositionId,n),t.endWidgetLoad(i.compositionId,!1),te.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){te.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:Yi,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 te.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),te.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):te.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,te.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 Kr})),o=n();return yield o.setContent(e,t,i)}catch(e){return te.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 Kr})),n=i();return yield n.getContentSchema(t.config.compositionId)}catch(e){throw te.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 Kr})),n=i();return yield n.getDesignSchema(t.config.compositionId)}catch(e){throw te.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 Kr})),n=t();return yield n.validateContent(e,i)}catch(e){throw te.error("[EmbedSDK] Failed to validate content:",e),e}}))}getContent(e){try{return Fr().getContent(e)}catch(e){return te.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):te.warn("Overlay manager not initialized")}hideOverlay(){this.overlayManager?this.overlayManager.hideOverlay():te.warn("Overlay manager not initialized")}triggerOverlay(e,t={}){this.overlayManager?this.overlayManager.triggerOverlay(e,t):te.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 Xa=null;function Ya(e){return Xa||(Xa=new Ga(e)),Xa}"undefined"!=typeof document&&(Pa(),"undefined"!=typeof MutationObserver&&new MutationObserver((()=>{Pa()})).observe(document.documentElement,{childList:!0,subtree:!0}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>{hn.enabled&&te.info("DOM ready, auto-initializing SDK"),Ya().init().catch((e=>{te.error("Auto-initialization failed",{error:e})}))})):(hn.enabled&&te.info("DOM already ready, auto-initializing SDK"),setTimeout((()=>{Ya().init().catch((e=>{te.error("Auto-initialization failed",{error:e})}))}),0)));var Ja=Object.freeze({__proto__:null,EmbedSDK:Ga,getSDK:Ya});class Qa{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=Cr(),this.initialize()}static getInstance(){return Qa.instance||(Qa.instance=new Qa),Qa.instance}initialize(){this.initialized||(ro()?(this.loadStoredState(),this.cleanupOldEntries(),this.initialized=!0,te.info("[TextFieldManager] Initialized successfully")):te.warn("[TextFieldManager] localStorage not available, text persistence disabled"))}registerTextField(e,t,i={}){const n=this.generateStateKey(e,t);te.debug(`[TextFieldManager] Registering text field: ${e}.${t}`,{config:i});const o=this.textStates.get(n);return o&&i.autoRestore&&this.shouldAutoRestore(o,i)&&te.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 te.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&&(te.warn(`[TextFieldManager] Text exceeds maxLength (${n.maxLength}), truncating`),d=r.substring(0,n.maxLength));const l={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,l),n.autoPersist&&n.persistState&&this.debouncePersist(a,n.debounceDelay||1e3),te.debug(`[TextFieldManager] Updated text field: ${a}`,{textLength:d.length,textType:l.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(),te.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(),te.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 te.info("[TextFieldManager] Storage version mismatch, clearing stored data"),void localStorage.removeItem(this.storageKey);t.textStates&&(this.textStates=new Map(Object.entries(t.textStates)),te.debug(`[TextFieldManager] Loaded ${this.textStates.size} text field states from storage`)),"boolean"==typeof t.autoRestoreEnabled&&(this.autoRestoreEnabled=t.autoRestoreEnabled)}catch(e){te.warn("[TextFieldManager] Failed to load stored state:",e),localStorage.removeItem(this.storageKey)}}persistState(){if(ro())try{const e={version:this.storageVersion,textStates:Object.fromEntries(this.textStates),timestamp:Date.now(),autoRestoreEnabled:this.autoRestoreEnabled};localStorage.setItem(this.storageKey,JSON.stringify(e)),te.debug(`[TextFieldManager] Persisted state for ${this.textStates.size} text fields`)}catch(e){te.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(),te.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(),te.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(),ro()&&localStorage.removeItem(this.storageKey),te.debug("[TextFieldManager] Cleaned up all data")}configureSecurity(e){this.securityManager.updateConfig(e),te.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),te.info(`[TextFieldManager] Unblocked instance: ${e}`)}getSecurityStats(){return this.securityManager.getSecurityStats()}validateText(e,t,i,n){return this.securityManager.validateTextFieldUpdate(e,t,i,n)}}function Za(){return Qa.getInstance()}var ed=Object.freeze({__proto__:null,TextFieldManager:Qa,getTextField:function(e,t){return Za().getTextField(e,t)},getTextFieldManager:Za,registerTextField:function(e,t,i){return Za().registerTextField(e,t,i)},updateTextField:function(e,t,i,n,o){Za().updateTextField(e,t,i,n,o)}});e.BootstrapManager=bn,e.FastWidgetScanner=yn,e.ProgressiveChunkLoader=wn,e.getBootstrapStats=kn,e.initializeWidgeticFast=Tn}));
|
|
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-bootstrap"]={})}(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="",l=2500,c=2e3,u=100,h=50,g=.1,p=.05,m=1800,f=1200,v=800,y=600,w=3e3,b=2e3,I=5e5,k=3e5,T="50px",S=.1,C=3,A=3,E=1e3,R=10,x=5e3,M=36e5,W=6,O=!0,D=!0,L=!1,U="info",P="2.0.3",_="2.0.3";function z(){var e;return`${"undefined"!=typeof process&&"development"===(null===(e={NODE_ENV:"production"})||void 0===e?void 0:e.NODE_ENV)?q.DEV_API_URL:q.PROD_API_URL}${q.VERSION}`}const q={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},j="auto",B="inline",$="fixed",N=350,F=200,K=!1,H={CUSTOM_ELEMENTS:"undefined"!=typeof customElements,HTTP3:!1,RESIZE_OBSERVER:"undefined"!=typeof ResizeObserver},V=10,G=5e3,X=3;let Y=L;const J={get enabled(){return Y},logLevel:U},Q=["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 Z(e){if("string"==typeof e){const t=e.toLowerCase();for(const i of Q)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(Z);if("object"==typeof e){const t={};for(const[i,n]of Object.entries(e)){const e=i.toLowerCase();Q.some((t=>e.includes(t.toLowerCase())||e===t.toLowerCase()))&&"string"==typeof n&&n.length>0?t[i]=`[REDACTED_${n.length}_CHARS]`:t[i]=Z(n)}return t}return e}const ee=new class{constructor(e=J.logLevel){this.logLevels={debug:0,info:1,warn:2,error:3},this.currentLevel=this.logLevels[e]}shouldLog(e){return J.enabled&&this.logLevels[e]>=this.currentLevel}formatMessage(e,t,...i){const n=(new Date).toISOString();return[`${`[Widgetic SDK] [${e.toUpperCase()}] [${n}]`} ${t}`,...i.map(Z)]}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){Y=e}(e)}},te={debug:(e,...t)=>ee.debug(e,...t),info:(e,...t)=>ee.info(e,...t),warn:(e,...t)=>ee.warn(e,...t),error:(e,...t)=>ee.error(e,...t),setLevel:e=>ee.setLevel(e)};class ie{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 ne="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 oe="https://api.widgetic.com/v1".replace(/\/+$/,""),se="X-SDK-Version";class re{constructor(e){if(this.configuration={basePath:oe,headers:{},middleware:[]},"string"==typeof e){const t=(null==e?void 0:e.startsWith("Bearer "))?e.slice(7):e;this.configuration.apiKey=e=>ne(this,void 0,void 0,(function*(){return"authorization"===(null==e?void 0:e.toLowerCase())?`Bearer ${t}`:t})),this.configuration.accessToken=()=>ne(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||oe});if("string"==typeof e.accessToken&&e.accessToken){const t=e.accessToken,i=t.startsWith("Bearer ")?t.slice(7):t;this.configuration.apiKey=e=>ne(this,void 0,void 0,(function*(){return"authorization"===(null==e?void 0:e.toLowerCase())?`Bearer ${i}`:i})),this.configuration.accessToken=()=>ne(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:oe}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||he}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:()=>ne(this,void 0,void 0,(function*(){return e}))}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}}const ae=new re;class de{constructor(e=ae){this.configuration=e,this.fetchApi=(e,t)=>ne(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 ce(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 re)||(e=new re(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&&de.jsonRegex.test(e)}request(e,t){return ne(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 l="Response returned an error code",c=null;try{const e=yield d.json(),t=e.error,n=t&&"object"==typeof t?t.message:t;l=e.message||n||l;const o=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.code;"string"==typeof o&&o.length>0&&(c=o)}catch(e){try{l=yield d.text()}catch(e){l=a.statusText}}throw new le(a,l,c)}))}createFetchParams(e,t){return ne(this,void 0,void 0,(function*(){let i=(this.configuration.basePath||oe).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]:{}));Object.keys(n).some((e=>e.toLowerCase()===se.toLowerCase()))||(n[se]="@widgetic/api-sdk/1.0.42");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:()=>ne(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 l;l=a.body,d="undefined"!=typeof FormData&&l 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}}de.jsonRegex=new RegExp("^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$","i");class le extends Error{constructor(e,t,i=null){super(t),this.response=e,this.name="ResponseError",this.code=i}}class ce extends Error{constructor(e,t){super(t),this.cause=e,this.name="FetchError"}}class ue extends Error{constructor(e,t){super(t),this.field=e,this.name="RequiredError"}}function he(e,t=""){return Object.keys(e).map((i=>ge(i,e[i],t))).filter((e=>e.length>0)).join("&")}function ge(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 ge(e,Array.from(t),i)}return t instanceof Date?`${encodeURIComponent(n)}=${encodeURIComponent(t.toISOString())}`:t instanceof Object?he(t,n):`${encodeURIComponent(n)}=${encodeURIComponent(String(t))}`}class pe{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 ne(this,void 0,void 0,(function*(){const e=yield this.raw.json();return this.transformer(this.unwrapSuccessEnvelope(e))}))}}class me{constructor(e){this.raw=e}value(){return ne(this,void 0,void 0,(function*(){}))}}function fe(e){return function(e){if(null==e)return e;return{configured:e.configured,endpointId:null==e.endpointId?void 0:e.endpointId,url:null==e.url?void 0:e.url,createdAt:null==e.createdAt?void 0:new Date(e.createdAt),rotatedAt:null==e.rotatedAt?void 0:new Date(e.rotatedAt),previousSecretValidUntil:null==e.previousSecretValidUntil?void 0:new Date(e.previousSecretValidUntil),lastReceivedAt:null==e.lastReceivedAt?void 0:new Date(e.lastReceivedAt)}}(e)}function ve(e){return function(e){if(null==e)return e;return{configured:e.configured,endpointId:e.endpointId,url:e.url,secret:e.secret,createdAt:new Date(e.createdAt),rotatedAt:null==e.rotatedAt?void 0:new Date(e.rotatedAt),previousSecretValidUntil:null==e.previousSecretValidUntil?void 0:new Date(e.previousSecretValidUntil),lastReceivedAt:null==e.lastReceivedAt?void 0:new Date(e.lastReceivedAt)}}(e)}function ye(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,goalTarget:null==e.goalTarget?void 0:e.goalTarget,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 we(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(ye)}}(e)}function be(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 Ie(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 ke(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 Te(e){return function(e){if(null==e)return e;return{detected:null==e.detected?void 0:e.detected,pValue:null==e.pValue?void 0:e.pValue}}(e)}function Se(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,totalImpressionEvents:null==e.totalImpressionEvents?void 0:e.totalImpressionEvents,totalConversionEvents:null==e.totalConversionEvents?void 0:e.totalConversionEvents,counting:null==e.counting?void 0:e.counting,overallConversionRate:null==e.overallConversionRate?void 0:e.overallConversionRate,statisticalPower:null==e.statisticalPower?void 0:e.statisticalPower,sampleSizeNeededPerVariant:null==e.sampleSizeNeededPerVariant?void 0:e.sampleSizeNeededPerVariant,sampleRatioMismatch:null==e.sampleRatioMismatch?void 0:Te(e.sampleRatioMismatch),confidenceLevel:null==e.confidenceLevel?void 0:e.confidenceLevel}}(e)}function Ce(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,rawImpressions:null==e.rawImpressions?void 0:e.rawImpressions,rawConversions:null==e.rawConversions?void 0:e.rawConversions,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,significantlyWorse:null==e.significantlyWorse?void 0:e.significantlyWorse,bayesianProbabilityToBeatControl:null==e.bayesianProbabilityToBeatControl?void 0:e.bayesianProbabilityToBeatControl}}(e)}function Ae(e){return function(e){if(null==e)return e;return{overall:null==e.overall?void 0:Se(e.overall),variants:null==e.variants?void 0:e.variants.map(Ce),recommendation:null==e.recommendation?void 0:ke(e.recommendation)}}(e)}function Ee(e){return function(e){if(null==e)return e;return{id:e.id,title:e.title,status:e.status,charCount:e.charCount,chunkCount:e.chunkCount,createdAt:new Date(e.createdAt),readyAt:null==e.readyAt?null:new Date(e.readyAt)}}(e)}function Re(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 xe(e){return function(e){if(null==e)return e;return{documents:e.documents,characters:e.characters,maxDocuments:e.maxDocuments,maxTotalChars:e.maxTotalChars}}(e)}function Me(e){return function(e){if(null==e)return e;return{documents:e.documents.map(Ee),totals:xe(e.totals)}}(e)}function We(e){return function(e){if(null==e)return e;return{removed:e.removed}}(e)}function Oe(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 De(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 Le(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 Ue(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Le(e.data)}}(e)}function Pe(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,contentVersion:null==e.contentVersion?void 0:e.contentVersion,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,direct:null==e.direct?void 0:e.direct}}(e)}function _e(e){return function(e){if(null==e)return e;return{url:e.url,refreshSeconds:e.refreshSeconds}}(e)}function ze(e){return function(e){if(null==e)return e;return{name:e.name,type:e.type}}(e)}function qe(e){return function(e){if(null==e)return e;return{name:e.name,columns:e.columns.map(ze),rows:e.rows}}(e)}function je(e){return function(e){if(null==e)return e;return{compositionId:e.compositionId,hasData:e.hasData,tables:e.tables.map(qe)}}(e)}function Be(e){return function(e){if(null==e)return e;return{value:e.value,count:e.count}}(e)}function $e(e){return function(e){if(null==e)return e;return{group:null==e.group?void 0:e.group,count:null==e.count?void 0:e.count,avg:null==e.avg?void 0:e.avg,min:null==e.min?void 0:e.min,max:null==e.max?void 0:e.max,sum:null==e.sum?void 0:e.sum}}(e)}function Ne(e){return function(e){if(null==e)return e;return{column:e.column,tallies:e.tallies.map($e),truncated:null==e.truncated?void 0:e.truncated}}(e)}function Fe(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(Be),moreGroups:e.moreGroups,columns:e.columns,rows:null==e.rows?null:e.rows,moreRows:e.moreRows,aggregates:null==e.aggregates?void 0:Ne(e.aggregates)}}(e)}function Ke(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 He(e){return function(e){if(null==e)return e;return{path:e.path,message:e.message,expected:null==e.expected?void 0:e.expected,actual:null==e.actual?void 0:e.actual}}(e)}function Ve(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 Ge(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,contentVersion:null==e.contentVersion?void 0:e.contentVersion,validationResult:null==e.validationResult?void 0:Ve(e.validationResult),compositionUpdated:null==e.compositionUpdated?void 0:e.compositionUpdated,realtimeUpdateSent:null==e.realtimeUpdateSent?void 0:e.realtimeUpdateSent,item:null==e.item?void 0:e.item}}(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:be(e.data)}}(e)}function Ye(e){return function(e){if(null==e)return e;return{name:e.name,description:e.description,compositionId:e.compositionId,trafficPercentage:e.trafficPercentage,goalTarget:e.goalTarget}}(e,!1)}function Je(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(Ye),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 Qe(e){return function(e){if(null==e)return e;return{warnings:null==e.warnings?void 0:e.warnings}}(e)}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:Pe(e.data),meta:null==e.meta?void 0:Qe(e.meta)}}(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:Ge(e.data)}}(e)}function tt(e){return function(e){if(null==e)return e;return Object.assign(Object.assign({},e),{position:e.position})}(e,!1)}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}}(e)}function nt(e){return function(e){if(null==e)return e;return{warnings:null==e.warnings?void 0:e.warnings}}(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:Pe(e.data),meta:null==e.meta?void 0:nt(e.meta)}}(e)}function st(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,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,lastCommitSha:null==e.lastCommitSha?void 0:e.lastCommitSha,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 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:st(e.data),meta:null==e.meta?void 0:e.meta}}(e)}function at(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:ve(e.data)}}(e)}function dt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:we(e.data)}}(e)}function lt(e){return function(e){if(null==e)return e;return{deleted:null==e.deleted?void 0:e.deleted,contentVersion:null==e.contentVersion?void 0:e.contentVersion}}(e)}function ct(e){return function(e){if(null==e)return e;return{removed:e.removed}}(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:ct(e.data)}}(e)}function ht(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 gt(e){return function(e){if(null==e)return e;return{operationId:null==e.operationId?void 0:e.operationId}}(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:gt(e.data)}}(e)}function mt(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,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,lastCommitSha:null==e.lastCommitSha?void 0:e.lastCommitSha,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 ft(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:mt(e.data),warnings:null==e.warnings?void 0:e.warnings}}(e)}function vt(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 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{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,goal_target:null==e.goal_target?void 0:e.goal_target}}(e)}function bt(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(wt),success_metrics:null==e.success_metrics?void 0:e.success_metrics,primary_metric:null==e.primary_metric?void 0:e.primary_metric}}(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:Me(e.data)}}(e)}function kt(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 Tt(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(Pe),meta:null==e.meta?void 0:kt(e.meta)}}(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,tracking:null==e.tracking?void 0:e.tracking,supportsElementTarget:null==e.supportsElementTarget?void 0:e.supportsElementTarget,available:null==e.available?void 0:e.available,unavailableReason:null==e.unavailableReason?void 0:e.unavailableReason}}(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(St)}}(e)}function At(e){return function(e){if(null==e)return e;return{selector:null==e.selector?void 0:e.selector,label:null==e.label?void 0:e.label,kind:null==e.kind?void 0:e.kind,tag:null==e.tag?void 0:e.tag,metrics:null==e.metrics?void 0:e.metrics,preferred:null==e.preferred?void 0:e.preferred,matchCount:null==e.matchCount?void 0:e.matchCount}}(e)}function Et(e){return function(e){if(null==e)return e;return{metric:null==e.metric?void 0:e.metric,label:null==e.label?void 0:e.label,description:null==e.description?void 0:e.description,selector:null==e.selector?void 0:e.selector,recommended:null==e.recommended?void 0:e.recommended}}(e)}function Rt(e){return function(e){if(null==e)return e;return{compositionId:null==e.compositionId?void 0:e.compositionId,complete:null==e.complete?void 0:e.complete,note:null==e.note?void 0:e.note,goals:null==e.goals?void 0:e.goals.map(Et),targets:null==e.targets?void 0:e.targets.map(At)}}(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:Rt(e.data)}}(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:Pe(e.data)}}(e)}function Wt(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 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}}(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 Lt(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 Ut(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 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(Ke)}}(e)}function _t(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 zt(e){return function(e){if(null==e)return e;return{compositions:null==e.compositions?void 0:e.compositions.map(Pe),errors:null==e.errors?void 0:e.errors.map(_t)}}(e)}function qt(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 jt(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 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:e.data.map(jt)}}(e)}function $t(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 Nt(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(mt),meta:null==e.meta?void 0:$t(e.meta)}}(e)}function Ft(e){return function(e){if(null==e)return e;return{widgets:null==e.widgets?void 0:e.widgets.map(mt),errors:null==e.errors?void 0:e.errors.map(_t)}}(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:fe(e.data)}}(e)}function Ht(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Ie(e.data)}}(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:Ae(e.data)}}(e)}function Gt(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 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(we),meta:null==e.meta?void 0:Gt(e.meta)}}(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:e.data}}(e)}function Jt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:We(e.data)}}(e)}function Qt(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 Zt(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Qt(e.data)}}(e)}function ei(e){return function(e){if(null==e)return e;return{email:e.email}}(e,!1)}function ti(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 ii(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,contentVersion:null==e.contentVersion?void 0:e.contentVersion,validationResult:null==e.validationResult?void 0:ti(e.validationResult),compositionUpdated:null==e.compositionUpdated?void 0:e.compositionUpdated,realtimeUpdateSent:null==e.realtimeUpdateSent?void 0:e.realtimeUpdateSent}}(e)}function ni(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 oi(e){return function(e){if(null==e)return e;return{data:null==e.data?void 0:ni(e.data),message:null==e.message?void 0:e.message,warnings:null==e.warnings?void 0:e.warnings}}(e)}function si(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:oi(e.data)}}(e)}function ri(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:we(e.data),message:null==e.message?void 0:e.message}}(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:we(e.data),message:null==e.message?void 0:e.message}}(e)}function di(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 li(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,goal_target:e.goal_target,timestamp:null==e.timestamp?void 0:e.timestamp.toISOString(),user_id:e.user_id,session_id:e.session_id}}(e,!1)}function ci(e){return function(e){if(null==e)return e;return{event_type:e.event_type,data:li(e.data)}}(e,!1)}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,count:null==e.count?void 0:e.count}}(e)}function hi(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,goal_target:e.goal_target,user_id:e.user_id,session_id:e.session_id,timestamp:null==e.timestamp?void 0:e.timestamp.toISOString()}}(e,!1)}function gi(e){return function(e){if(null==e)return e;return{event_type:e.event_type,data:hi(e.data)}}(e,!1)}function pi(e){return function(e){if(null==e)return e;return{events:e.events.map(gi)}}(e,!1)}function mi(e){return function(e){if(null==e)return e;return{id:e.id,goalTarget:e.goalTarget}}(e,!1)}function fi(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,variants:null==e.variants?void 0:e.variants.map(mi),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 vi(e){return function(e){if(null==e)return e;return{token:e.token,email:e.email}}(e,!1)}function yi(e){return function(e){if(null==e)return e;return{repositoryId:null==e.repositoryId?void 0:e.repositoryId}}(e)}function wi(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:yi(e.data),meta:null==e.meta?void 0:e.meta}}(e)}function bi(e){return function(e){if(null==e)return e;return{thumbnailUrl:null==e.thumbnailUrl?void 0:e.thumbnailUrl}}(e)}function Ii(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:bi(e.data)}}(e)}function ki(e){return function(e){if(null==e)return e;return{valid:e.valid,errors:null==e.errors?void 0:e.errors.map(He),warnings:null==e.warnings?void 0:e.warnings.map(He),sanitizedContent:null==e.sanitizedContent?void 0:e.sanitizedContent}}(e)}function Ti(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 Si(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 Ci(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 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 Ei(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 Ri(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 xi(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(Ri),warnings:null==e.warnings?void 0:e.warnings.map(Ei)}}(e)}function Mi(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:xi(e.data)}}(e)}function Wi(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 Oi(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(Wi),recommendations:null==e.recommendations?void 0:e.recommendations}}(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:Oi(e.data)}}(e)}function Li(e){return function(e){if(null==e)return e;return{composition_id:e.composition_id,name:e.name}}(e,!1)}function Ui(e){return function(e){if(null==e)return e;return{variants:e.variants.map(Li),success_metrics:e.success_metrics}}(e,!1)}function Pi(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(Ri),warnings:null==e.warnings?void 0:e.warnings.map(Ei)}}(e)}function _i(e){return function(e){if(null==e)return e;return{success:null==e.success?void 0:e.success,data:null==e.data?void 0:Pi(e.data)}}(e)}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 de{assignVariantRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling assignVariant().');if(null==e.assignVariantRequest)throw new ue("assignVariantRequest",'Required parameter "assignVariantRequest" was null or undefined when calling assignVariant().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const 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 pe(n,(e=>ye(e)))}))}assignVariant(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.assignVariantRaw(e,t);return yield i.value()}))}checkWorkspaceABTestAutoStopRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling checkWorkspaceABTestAutoStop().');if(null==e.testId)throw new ue("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 pe(n,(e=>Ue(e)))}))}checkWorkspaceABTestAutoStop(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.checkWorkspaceABTestAutoStopRaw(e,t);return yield i.value()}))}createABTestAssignmentRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.createABTestAssignmentRequest)throw new ue("createABTestAssignmentRequest",'Required parameter "createABTestAssignmentRequest" was null or undefined when calling createABTestAssignment().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const 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 pe(n,(e=>Xe(e)))}))}createABTestAssignment(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.createABTestAssignmentRaw(e,t);return yield i.value()}))}createWorkspaceABConversionWebhookRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling createWorkspaceABConversionWebhook().');const i={};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:"/workspaces/{workspaceId}/ab-conversion-webhook".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"POST",headers:i,query:{}},t);return new pe(n,(e=>at(e)))}))}createWorkspaceABConversionWebhook(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.createWorkspaceABConversionWebhookRaw(e,t);return yield i.value()}))}createWorkspaceABTestRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling createWorkspaceABTest().');if(null==e.createABTestRequest)throw new ue("createABTestRequest",'Required parameter "createABTestRequest" was null or undefined when calling createWorkspaceABTest().');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:"/workspaces/{workspaceId}/ab-tests".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"POST",headers:i,query:{},body:Je(e.createABTestRequest)},t);return new pe(n,(e=>dt(e)))}))}createWorkspaceABTest(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.createWorkspaceABTestRaw(e,t);return yield i.value()}))}deleteWorkspaceABConversionWebhookRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling deleteWorkspaceABConversionWebhook().');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-conversion-webhook".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"DELETE",headers:i,query:{}},t);return new pe(n,(e=>ut(e)))}))}deleteWorkspaceABConversionWebhook(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.deleteWorkspaceABConversionWebhookRaw(e,t);return yield i.value()}))}deleteWorkspaceABTestRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling deleteWorkspaceABTest().');if(null==e.testId)throw new ue("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 pe(n,(e=>ht(e)))}))}deleteWorkspaceABTest(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.deleteWorkspaceABTestRaw(e,t);return yield i.value()}))}getABTestConfigRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 pe(i,(e=>bt(e)))}))}getABTestConfig(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.getABTestConfigRaw(e,t);return yield i.value()}))}getAvailableMetricsRaw(e){return zi(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 pe(i,(e=>Ct(e)))}))}getAvailableMetrics(e){return zi(this,void 0,void 0,(function*(){const t=yield this.getAvailableMetricsRaw(e);return yield t.value()}))}getCompositionABGoalTargetsRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling getCompositionABGoalTargets().');if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionABGoalTargets().');const i={};null!=e.metric&&(i.metric=e.metric);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}/compositions/{id}/ab-goal-targets".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))).replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:n,query:i},t);return new pe(o,(e=>xt(e)))}))}getCompositionABGoalTargets(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.getCompositionABGoalTargetsRaw(e,t);return yield i.value()}))}getVariantConfigRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 pe(i,(e=>qt(e)))}))}getVariantConfig(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.getVariantConfigRaw(e,t);return yield i.value()}))}getWorkspaceABConversionWebhookRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling getWorkspaceABConversionWebhook().');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-conversion-webhook".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"GET",headers:i,query:{}},t);return new pe(n,(e=>Kt(e)))}))}getWorkspaceABConversionWebhook(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.getWorkspaceABConversionWebhookRaw(e,t);return yield i.value()}))}getWorkspaceABTestRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling getWorkspaceABTest().');if(null==e.testId)throw new ue("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 pe(n,(e=>dt(e)))}))}getWorkspaceABTest(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.getWorkspaceABTestRaw(e,t);return yield i.value()}))}getWorkspaceABTestDiagnosisRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling getWorkspaceABTestDiagnosis().');if(null==e.testId)throw new ue("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 pe(n,(e=>Ht(e)))}))}getWorkspaceABTestDiagnosis(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.getWorkspaceABTestDiagnosisRaw(e,t);return yield i.value()}))}getWorkspaceABTestStatisticsRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling getWorkspaceABTestStatistics().');if(null==e.testId)throw new ue("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 pe(n,(e=>Vt(e)))}))}getWorkspaceABTestStatistics(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.getWorkspaceABTestStatisticsRaw(e,t);return yield i.value()}))}listWorkspaceABTestsRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("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 pe(o,(e=>Xt(e)))}))}listWorkspaceABTests(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.listWorkspaceABTestsRaw(e,t);return yield i.value()}))}pauseWorkspaceABTestRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling pauseWorkspaceABTest().');if(null==e.testId)throw new ue("testId",'Required parameter "testId" was null or undefined when calling pauseWorkspaceABTest().');const i={};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:"/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 pe(n,(e=>dt(e)))}))}pauseWorkspaceABTest(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.pauseWorkspaceABTestRaw(e,t);return yield i.value()}))}rotateWorkspaceABConversionWebhookSecretRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling rotateWorkspaceABConversionWebhookSecret().');const i={};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:"/workspaces/{workspaceId}/ab-conversion-webhook/rotate".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"POST",headers:i,query:{}},t);return new pe(n,(e=>at(e)))}))}rotateWorkspaceABConversionWebhookSecret(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.rotateWorkspaceABConversionWebhookSecretRaw(e,t);return yield i.value()}))}setWorkspaceABTestDurationRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling setWorkspaceABTestDuration().');if(null==e.testId)throw new ue("testId",'Required parameter "testId" was null or undefined when calling setWorkspaceABTestDuration().');if(null==e.setWorkspaceABTestDurationRequest)throw new ue("setWorkspaceABTestDurationRequest",'Required parameter "setWorkspaceABTestDurationRequest" was null or undefined when calling setWorkspaceABTestDuration().');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:"/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 pe(n,(e=>ri(e)))}))}setWorkspaceABTestDuration(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.setWorkspaceABTestDurationRaw(e,t);return yield i.value()}))}startWorkspaceABTestRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling startWorkspaceABTest().');if(null==e.testId)throw new ue("testId",'Required parameter "testId" was null or undefined when calling startWorkspaceABTest().');const i={};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:"/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 pe(n,(e=>dt(e)))}))}startWorkspaceABTest(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.startWorkspaceABTestRaw(e,t);return yield i.value()}))}stopWorkspaceABTestRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling stopWorkspaceABTest().');if(null==e.testId)throw new ue("testId",'Required parameter "testId" was null or undefined when calling stopWorkspaceABTest().');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:"/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 pe(n,(e=>ai(e)))}))}stopWorkspaceABTest(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.stopWorkspaceABTestRaw(e,t);return yield i.value()}))}trackABTestEventRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.trackABTestEventRequest)throw new ue("trackABTestEventRequest",'Required parameter "trackABTestEventRequest" was null or undefined when calling trackABTestEvent().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const n=yield this.request({path:"/ab-tests/analytics/events",method:"POST",headers:i,query:{},body:ci(e.trackABTestEventRequest)},t);return new pe(n,(e=>di(e)))}))}trackABTestEvent(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.trackABTestEventRaw(e,t);return yield i.value()}))}trackBulkABTestEventsRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.trackBulkABTestEventsRequest)throw new ue("trackBulkABTestEventsRequest",'Required parameter "trackBulkABTestEventsRequest" was null or undefined when calling trackBulkABTestEvents().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const n=yield this.request({path:"/ab-tests/analytics/bulk",method:"POST",headers:i,query:{},body:pi(e.trackBulkABTestEventsRequest)},t);return new pe(n,(e=>ui(e)))}))}trackBulkABTestEvents(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.trackBulkABTestEventsRaw(e,t);return yield i.value()}))}updateWorkspaceABTestRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling updateWorkspaceABTest().');if(null==e.testId)throw new ue("testId",'Required parameter "testId" was null or undefined when calling updateWorkspaceABTest().');if(null==e.updateABTestRequest)throw new ue("updateABTestRequest",'Required parameter "updateABTestRequest" was null or undefined when calling updateWorkspaceABTest().');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:"/workspaces/{workspaceId}/ab-tests/{testId}".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))).replace("{testId}",encodeURIComponent(String(e.testId))),method:"PUT",headers:i,query:{},body:fi(e.updateABTestRequest)},t);return new pe(n,(e=>dt(e)))}))}updateWorkspaceABTest(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.updateWorkspaceABTestRaw(e,t);return yield i.value()}))}validateWorkspaceCompositionDeletionRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling validateWorkspaceCompositionDeletion().');if(null==e.validateWorkspaceCompositionDeletionRequest)throw new ue("validateWorkspaceCompositionDeletionRequest",'Required parameter "validateWorkspaceCompositionDeletionRequest" was null or undefined when calling validateWorkspaceCompositionDeletion().');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:"/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 pe(n,(e=>Mi(e)))}))}validateWorkspaceCompositionDeletion(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.validateWorkspaceCompositionDeletionRaw(e,t);return yield i.value()}))}validateWorkspaceGoalTrackingRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling validateWorkspaceGoalTracking().');if(null==e.validateWorkspaceGoalTrackingRequest)throw new ue("validateWorkspaceGoalTrackingRequest",'Required parameter "validateWorkspaceGoalTrackingRequest" was null or undefined when calling validateWorkspaceGoalTracking().');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:"/workspaces/{workspaceId}/ab-tests/validate-goal-tracking".replace("{workspaceId}",encodeURIComponent(String(e.workspaceId))),method:"POST",headers:i,query:{},body:Ui(e.validateWorkspaceGoalTrackingRequest)},t);return new pe(n,(e=>Di(e)))}))}validateWorkspaceGoalTracking(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.validateWorkspaceGoalTrackingRaw(e,t);return yield i.value()}))}validateWorkspaceWidgetDeletionRaw(e,t){return zi(this,void 0,void 0,(function*(){if(null==e.workspaceId)throw new ue("workspaceId",'Required parameter "workspaceId" was null or undefined when calling validateWorkspaceWidgetDeletion().');if(null==e.validateWorkspaceWidgetDeletionRequest)throw new ue("validateWorkspaceWidgetDeletionRequest",'Required parameter "validateWorkspaceWidgetDeletionRequest" was null or undefined when calling validateWorkspaceWidgetDeletion().');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:"/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 pe(n,(e=>_i(e)))}))}validateWorkspaceWidgetDeletion(e,t){return zi(this,void 0,void 0,(function*(){const i=yield this.validateWorkspaceWidgetDeletionRaw(e,t);return yield i.value()}))}}var ji="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 de{completeSignupRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.completeSignupRequest)throw new ue("completeSignupRequest",'Required parameter "completeSignupRequest" was null or undefined when calling completeSignup().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const 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 me(n)}))}completeSignup(e,t){return ji(this,void 0,void 0,(function*(){yield this.completeSignupRaw(e,t)}))}confirmEmailRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.updateEmailRequest)throw new ue("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:vi(e.updateEmailRequest)},t);return new me(n)}))}confirmEmail(e,t){return ji(this,void 0,void 0,(function*(){yield this.confirmEmailRaw(e,t)}))}consumeOAuthSessionBridgeRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.bridgeId)throw new ue("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 me(i)}))}consumeOAuthSessionBridge(e,t){return ji(this,void 0,void 0,(function*(){yield this.consumeOAuthSessionBridgeRaw(e,t)}))}deleteAccountRaw(e,t){return ji(this,void 0,void 0,(function*(){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:"/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 me(n)}))}deleteAccount(){return ji(this,arguments,void 0,(function*(e={},t){yield this.deleteAccountRaw(e,t)}))}getSessionRaw(e){return ji(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 me(i)}))}getSession(e){return ji(this,void 0,void 0,(function*(){yield this.getSessionRaw(e)}))}getUserMetadataRaw(e){return ji(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 me(i)}))}getUserMetadata(e){return ji(this,void 0,void 0,(function*(){yield this.getUserMetadataRaw(e)}))}initiateOAuthRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.provider)throw new ue("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 me(n)}))}initiateOAuth(e,t){return ji(this,void 0,void 0,(function*(){yield this.initiateOAuthRaw(e,t)}))}loginUserRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.loginUserRequest)throw new ue("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 pe(n,(e=>Yt(e)))}))}loginUser(e,t){return ji(this,void 0,void 0,(function*(){const i=yield this.loginUserRaw(e,t);return yield i.value()}))}logoutUserRaw(e){return ji(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 me(i)}))}logoutUser(e){return ji(this,void 0,void 0,(function*(){yield this.logoutUserRaw(e)}))}refreshSessionRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.refreshSessionRequest)throw new ue("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 me(n)}))}refreshSession(e,t){return ji(this,void 0,void 0,(function*(){yield this.refreshSessionRaw(e,t)}))}resendConfirmationRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.resetPasswordRequest)throw new ue("resetPasswordRequest",'Required parameter "resetPasswordRequest" was null or undefined when calling resendConfirmation().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const n=yield this.request({path:"/auth/resend-confirmation",method:"POST",headers:i,query:{},body:ei(e.resetPasswordRequest)},t);return new me(n)}))}resendConfirmation(e,t){return ji(this,void 0,void 0,(function*(){yield this.resendConfirmationRaw(e,t)}))}resetPasswordRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.resetPasswordRequest)throw new ue("resetPasswordRequest",'Required parameter "resetPasswordRequest" was null or undefined when calling resetPassword().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const n=yield this.request({path:"/auth/reset-password",method:"POST",headers:i,query:{},body:ei(e.resetPasswordRequest)},t);return new me(n)}))}resetPassword(e,t){return ji(this,void 0,void 0,(function*(){yield this.resetPasswordRaw(e,t)}))}signupUserRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.signupUserRequest)throw new ue("signupUserRequest",'Required parameter "signupUserRequest" was null or undefined when calling signupUser().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const 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 me(n)}))}signupUser(e,t){return ji(this,void 0,void 0,(function*(){yield this.signupUserRaw(e,t)}))}signupWithInvitationRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.signupWithInvitationRequest)throw new ue("signupWithInvitationRequest",'Required parameter "signupWithInvitationRequest" was null or undefined when calling signupWithInvitation().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const 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 me(n)}))}signupWithInvitation(e,t){return ji(this,void 0,void 0,(function*(){yield this.signupWithInvitationRaw(e,t)}))}updateEmailRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.updateEmailRequest)throw new ue("updateEmailRequest",'Required parameter "updateEmailRequest" was null or undefined when calling updateEmail().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const n=yield this.request({path:"/auth/update-email",method:"POST",headers:i,query:{},body:vi(e.updateEmailRequest)},t);return new me(n)}))}updateEmail(e,t){return ji(this,void 0,void 0,(function*(){yield this.updateEmailRaw(e,t)}))}updateNameRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.updateNameRequest)throw new ue("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 me(n)}))}updateName(e,t){return ji(this,void 0,void 0,(function*(){yield this.updateNameRaw(e,t)}))}updatePasswordRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.updatePasswordRequest)throw new ue("updatePasswordRequest",'Required parameter "updatePasswordRequest" was null or undefined when calling updatePassword().');const i={"Content-Type":"application/json"};null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey));const 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 me(n)}))}updatePassword(e,t){return ji(this,void 0,void 0,(function*(){yield this.updatePasswordRaw(e,t)}))}updateUserMetadataRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.updateUserMetadataRequest)throw new ue("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 me(n)}))}updateUserMetadata(e,t){return ji(this,void 0,void 0,(function*(){yield this.updateUserMetadataRaw(e,t)}))}validateInviteCodeRaw(e,t){return ji(this,void 0,void 0,(function*(){if(null==e.code)throw new ue("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 pe(n,(e=>Si(e)))}))}validateInviteCode(e,t){return ji(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 Ni extends de{addAiAnswersKnowledgeDocumentRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling addAiAnswersKnowledgeDocument().');if(null==e.addAiAnswersKnowledgeDocumentRequest)throw new ue("addAiAnswersKnowledgeDocumentRequest",'Required parameter "addAiAnswersKnowledgeDocumentRequest" was null or undefined when calling addAiAnswersKnowledgeDocument().');const i={"Content-Type":"application/json"};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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}/adapters/ai-answers/knowledge/documents".replace("{id}",encodeURIComponent(String(e.id))),method:"POST",headers:i,query:{},body:(s=e.addAiAnswersKnowledgeDocumentRequest,o=s,null==o?o:{title:o.title,text:o.text})},t);var o,s;return new pe(n,(e=>Re(e)))}))}addAiAnswersKnowledgeDocument(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.addAiAnswersKnowledgeDocumentRaw(e,t);return yield i.value()}))}checkCompositionAccessRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 pe(n,(e=>Oe(e)))}))}checkCompositionAccess(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.checkCompositionAccessRaw(e,t);return yield i.value()}))}createCompositionContentItemRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling createCompositionContentItem().');if(null==e.list)throw new ue("list",'Required parameter "list" was null or undefined when calling createCompositionContentItem().');if(null==e.createCompositionContentItemRequest)throw new ue("createCompositionContentItemRequest",'Required parameter "createCompositionContentItemRequest" was null or undefined when calling createCompositionContentItem().');const i={"Content-Type":"application/json"};if(null!=e.ifMatch&&(i["If-Match"]=String(e.ifMatch)),null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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/{list}/items".replace("{id}",encodeURIComponent(String(e.id))).replace("{list}",encodeURIComponent(String(e.list))),method:"POST",headers:i,query:{},body:tt(e.createCompositionContentItemRequest)},t);return new pe(n,(e=>et(e)))}))}createCompositionContentItem(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.createCompositionContentItemRaw(e,t);return yield i.value()}))}createCompositionDatabaseRecordRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling createCompositionDatabaseRecord().');if(null==e.table)throw new ue("table",'Required parameter "table" was null or undefined when calling createCompositionDatabaseRecord().');if(null==e.body)throw new ue("body",'Required parameter "body" was null or undefined when calling createCompositionDatabaseRecord().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>it(e)))}))}createCompositionDatabaseRecord(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.createCompositionDatabaseRecordRaw(e,t);return yield i.value()}))}createCompositionRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.newComposition)throw new ue("newComposition",'Required parameter "newComposition" was null or undefined when calling createComposition().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(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()}))}deleteCompositionContentItemRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling deleteCompositionContentItem().');if(null==e.list)throw new ue("list",'Required parameter "list" was null or undefined when calling deleteCompositionContentItem().');if(null==e.itemId)throw new ue("itemId",'Required parameter "itemId" was null or undefined when calling deleteCompositionContentItem().');const i={};if(null!=e.ifMatch&&(i["If-Match"]=String(e.ifMatch)),null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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/{list}/items/{itemId}".replace("{id}",encodeURIComponent(String(e.id))).replace("{list}",encodeURIComponent(String(e.list))).replace("{itemId}",encodeURIComponent(String(e.itemId))),method:"DELETE",headers:i,query:{}},t);return new pe(n,(e=>lt(e)))}))}deleteCompositionContentItem(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.deleteCompositionContentItemRaw(e,t);return yield i.value()}))}deleteCompositionDataSourceRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling deleteCompositionDataSource().');const i={};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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}/data-source".replace("{id}",encodeURIComponent(String(e.id))),method:"DELETE",headers:i,query:{}},t);return new pe(n,(e=>function(e){return null==e?e:{removed:e.removed}}(e)))}))}deleteCompositionDataSource(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.deleteCompositionDataSourceRaw(e,t);return yield i.value()}))}deleteCompositionDatabaseRecordRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling deleteCompositionDatabaseRecord().');if(null==e.table)throw new ue("table",'Required parameter "table" was null or undefined when calling deleteCompositionDatabaseRecord().');if(null==e.recordId)throw new ue("recordId",'Required parameter "recordId" was null or undefined when calling deleteCompositionDatabaseRecord().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>it(e)))}))}deleteCompositionDatabaseRecord(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.deleteCompositionDatabaseRecordRaw(e,t);return yield i.value()}))}deleteCompositionRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling deleteComposition().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 me(n)}))}deleteComposition(e,t){return $i(this,void 0,void 0,(function*(){yield this.deleteCompositionRaw(e,t)}))}describeCompositionEntriesRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling describeCompositionEntries().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>je(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 ue("id",'Required parameter "id" was null or undefined when calling duplicateComposition().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>pt(e)))}))}duplicateComposition(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.duplicateCompositionRaw(e,t);return yield i.value()}))}getAiAnswersKnowledgeRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getAiAnswersKnowledge().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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}/adapters/ai-answers/knowledge".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new pe(n,(e=>It(e)))}))}getAiAnswersKnowledge(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.getAiAnswersKnowledgeRaw(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.widgetId=e.widgetId),null!=e.workspace&&(i.workspace=e.workspace),null!=e.projectFolder&&(i.projectFolder=e.projectFolder),null!=e.status&&(i.status=e.status),null!=e.managedUserId&&(i.managedUserId=e.managedUserId),null!=e.managedUserExternalId&&(i.managedUserExternalId=e.managedUserExternalId);const n={};if(null!=e.xManagedUserId&&(n["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(n["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(o,(e=>Tt(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 ue("id",'Required parameter "id" was null or undefined when calling getCompositionById().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Mt(e)))}))}getCompositionById(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.getCompositionByIdRaw(e,t);return yield i.value()}))}getCompositionContentSchemaRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionContentSchema().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Wt(e)))}))}getCompositionContentSchema(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.getCompositionContentSchemaRaw(e,t);return yield i.value()}))}getCompositionContentRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionContent().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n)}))}getCompositionContent(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.getCompositionContentRaw(e,t);return yield i.value()}))}getCompositionDataSourceRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionDataSource().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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}/data-source".replace("{id}",encodeURIComponent(String(e.id))),method:"GET",headers:i,query:{}},t);return new pe(n,(e=>_e(e)))}))}getCompositionDataSource(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.getCompositionDataSourceRaw(e,t);return yield i.value()}))}getCompositionDatabaseRecordRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionDatabaseRecord().');if(null==e.table)throw new ue("table",'Required parameter "table" was null or undefined when calling getCompositionDatabaseRecord().');if(null==e.recordId)throw new ue("recordId",'Required parameter "recordId" was null or undefined when calling getCompositionDatabaseRecord().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>it(e)))}))}getCompositionDatabaseRecord(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.getCompositionDatabaseRecordRaw(e,t);return yield i.value()}))}getCompositionDatabaseRecordsRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionDatabaseRecords().');if(null==e.table)throw new ue("table",'Required parameter "table" was null or undefined when calling getCompositionDatabaseRecords().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Ot(e)))}))}getCompositionDatabaseRecords(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.getCompositionDatabaseRecordsRaw(e,t);return yield i.value()}))}getCompositionDesignSchemaRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionDesignSchema().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(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()}))}getCompositionDesignRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionDesign().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n)}))}getCompositionDesign(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.getCompositionDesignRaw(e,t);return yield i.value()}))}getCompositionEmbedSchemaRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling getCompositionEmbedSchema().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Lt(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 ue("id",'Required parameter "id" was null or undefined when calling getCompositionEmbedSettings().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(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 ue("id",'Required parameter "id" was null or undefined when calling getCompositionPreview().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Ut(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 ue("id",'Required parameter "id" was null or undefined when calling getCompositionVersions().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Pt(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 ue("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 pe(n,(e=>zt(e)))}))}getCompositionsBatch(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.getCompositionsBatchRaw(e,t);return yield i.value()}))}patchCompositionContentItemRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling patchCompositionContentItem().');if(null==e.list)throw new ue("list",'Required parameter "list" was null or undefined when calling patchCompositionContentItem().');if(null==e.itemId)throw new ue("itemId",'Required parameter "itemId" was null or undefined when calling patchCompositionContentItem().');if(null==e.requestBody)throw new ue("requestBody",'Required parameter "requestBody" was null or undefined when calling patchCompositionContentItem().');const i={"Content-Type":"application/json"};if(null!=e.ifMatch&&(i["If-Match"]=String(e.ifMatch)),null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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/{list}/items/{itemId}".replace("{id}",encodeURIComponent(String(e.id))).replace("{list}",encodeURIComponent(String(e.list))).replace("{itemId}",encodeURIComponent(String(e.itemId))),method:"PATCH",headers:i,query:{},body:e.requestBody},t);return new pe(n,(e=>et(e)))}))}patchCompositionContentItem(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.patchCompositionContentItemRaw(e,t);return yield i.value()}))}readCompositionEntriesRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling readCompositionEntries().');if(null==e.table)throw new ue("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),null!=e.aggregate&&(i.aggregate=e.aggregate),null!=e.column&&(i.column=e.column),null!=e.since&&(i.since=e.since.toISOString()),null!=e.until&&(i.until=e.until.toISOString()),null!=e.context&&(i.context=e.context),null!=e.filter&&(i.filter=e.filter);const n={};if(null!=e.xManagedUserId&&(n["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(n["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(o,(e=>Fe(e)))}))}readCompositionEntries(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.readCompositionEntriesRaw(e,t);return yield i.value()}))}removeAiAnswersKnowledgeDocumentRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling removeAiAnswersKnowledgeDocument().');if(null==e.documentId)throw new ue("documentId",'Required parameter "documentId" was null or undefined when calling removeAiAnswersKnowledgeDocument().');const i={};if(null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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}/adapters/ai-answers/knowledge/documents/{documentId}".replace("{id}",encodeURIComponent(String(e.id))).replace("{documentId}",encodeURIComponent(String(e.documentId))),method:"DELETE",headers:i,query:{}},t);return new pe(n,(e=>Jt(e)))}))}removeAiAnswersKnowledgeDocument(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.removeAiAnswersKnowledgeDocumentRaw(e,t);return yield i.value()}))}setCompositionDataSourceRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling setCompositionDataSource().');if(null==e.setCompositionDataSourceRequest)throw new ue("setCompositionDataSourceRequest",'Required parameter "setCompositionDataSourceRequest" was null or undefined when calling setCompositionDataSource().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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}/data-source".replace("{id}",encodeURIComponent(String(e.id))),method:"PUT",headers:i,query:{},body:(s=e.setCompositionDataSourceRequest,o=s,null==o?o:{url:o.url,refreshSeconds:o.refreshSeconds})},t);var o,s;return new pe(n,(e=>_e(e)))}))}setCompositionDataSource(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.setCompositionDataSourceRaw(e,t);return yield i.value()}))}setDynamicContentRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling setDynamicContent().');if(null==e.setDynamicContentRequest)throw new ue("setDynamicContentRequest",'Required parameter "setDynamicContentRequest" was null or undefined when calling setDynamicContent().');const i={"Content-Type":"application/json"};if(null!=e.ifMatch&&(i["If-Match"]=String(e.ifMatch)),null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>ii(e)))}))}setDynamicContent(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.setDynamicContentRaw(e,t);return yield i.value()}))}updateCompositionDatabaseRecordRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling updateCompositionDatabaseRecord().');if(null==e.table)throw new ue("table",'Required parameter "table" was null or undefined when calling updateCompositionDatabaseRecord().');if(null==e.recordId)throw new ue("recordId",'Required parameter "recordId" was null or undefined when calling updateCompositionDatabaseRecord().');if(null==e.body)throw new ue("body",'Required parameter "body" was null or undefined when calling updateCompositionDatabaseRecord().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>it(e)))}))}updateCompositionDatabaseRecord(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.updateCompositionDatabaseRecordRaw(e,t);return yield i.value()}))}updateCompositionStatusRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling updateCompositionStatus().');if(null==e.updateCompositionStatusRequest)throw new ue("updateCompositionStatusRequest",'Required parameter "updateCompositionStatusRequest" was null or undefined when calling updateCompositionStatus().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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 pe(n,(e=>Pe(e)))}))}updateCompositionStatus(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.updateCompositionStatusRaw(e,t);return yield i.value()}))}updateCompositionRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling updateComposition().');if(null==e.updateComposition)throw new ue("updateComposition",'Required parameter "updateComposition" was null or undefined when calling updateComposition().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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,databaseSchema:o.databaseSchema,projectId:o.projectId})},t);var o,s;return new pe(n,(e=>Mt(e)))}))}updateComposition(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.updateCompositionRaw(e,t);return yield i.value()}))}validateCompositionContentRaw(e,t){return $i(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling validateCompositionContent().');if(null==e.requestBody)throw new ue("requestBody",'Required parameter "requestBody" was null or undefined when calling validateCompositionContent().');const i={"Content-Type":"application/json"};if(null!=e.idempotencyKey&&(i["Idempotency-Key"]=String(e.idempotencyKey)),null!=e.xManagedUserId&&(i["X-Managed-User-Id"]=String(e.xManagedUserId)),null!=e.xManagedUserExternalId&&(i["X-Managed-User-External-Id"]=String(e.xManagedUserExternalId)),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.requestBody},t);return new pe(n,(e=>ki(e)))}))}validateCompositionContent(e,t){return $i(this,void 0,void 0,(function*(){const i=yield this.validateCompositionContentRaw(e,t);return yield i.value()}))}}var Fi="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 Ki extends de{exchangeTokenRaw(e,t){return Fi(this,void 0,void 0,(function*(){if(null==e.exchangeTokenRequest)throw new ue("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 pe(n,(e=>yt(e)))}))}exchangeToken(e,t){return Fi(this,void 0,void 0,(function*(){const i=yield this.exchangeTokenRaw(e,t);return yield i.value()}))}validateTokenRaw(e){return Fi(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 pe(i,(e=>Ai(e)))}))}validateToken(e){return Fi(this,void 0,void 0,(function*(){const t=yield this.validateTokenRaw(e);return yield t.value()}))}}var Hi="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 Vi extends de{checkWidgetAccessRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 pe(n,(e=>De(e)))}))}checkWidgetAccess(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.checkWidgetAccessRaw(e,t);return yield i.value()}))}createCompositionFromWidgetRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling createCompositionFromWidget().');if(null==e.createCompositionFromWidgetRequest)throw new ue("createCompositionFromWidgetRequest",'Required parameter "createCompositionFromWidgetRequest" was null or undefined when calling createCompositionFromWidget().');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/{id}/composition".replace("{id}",encodeURIComponent(String(e.id))),method:"POST",headers:i,query:{},body:(s=e.createCompositionFromWidgetRequest,o=s,null==o?o:{name:o.name,content:o.content,design:o.design,embedSettings:o.embedSettings,locale:o.locale,managedUserId:o.managedUserId})},t);var o,s;return new pe(n,(e=>ot(e)))}))}createCompositionFromWidget(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.createCompositionFromWidgetRaw(e,t);return yield i.value()}))}createWidgetRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.newWidget)throw new ue("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 pe(n,(e=>rt(e)))}))}createWidget(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.createWidgetRaw(e,t);return yield i.value()}))}deleteWidgetRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 me(n)}))}deleteWidget(e,t){return Hi(this,void 0,void 0,(function*(){yield this.deleteWidgetRaw(e,t)}))}detachWidgetRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 me(n)}))}detachWidget(e,t){return Hi(this,void 0,void 0,(function*(){yield this.detachWidgetRaw(e,t)}))}duplicateWidgetRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling duplicateWidget().');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("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 pe(n,(e=>ft(e)))}))}duplicateWidget(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.duplicateWidgetRaw(e,t);return yield i.value()}))}getWidgetContentSchemaRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 pe(n)}))}getWidgetContentSchema(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.getWidgetContentSchemaRaw(e,t);return yield i.value()}))}getWidgetDesignSchemaRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("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 pe(n)}))}getWidgetDesignSchema(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.getWidgetDesignSchemaRaw(e,t);return yield i.value()}))}getWidgetPublishHistoryRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.widgetId)throw new ue("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 pe(n,(e=>Bt(e)))}))}getWidgetPublishHistory(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.getWidgetPublishHistoryRaw(e,t);return yield i.value()}))}getWidgetsBatchRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.getWidgetsBatchRequest)throw new ue("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 pe(n,(e=>Ft(e)))}))}getWidgetsBatch(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.getWidgetsBatchRaw(e,t);return yield i.value()}))}getWidgetsRaw(e,t){return Hi(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 pe(o,(e=>Nt(e)))}))}getWidgets(){return Hi(this,arguments,void 0,(function*(e={},t){const i=yield this.getWidgetsRaw(e,t);return yield i.value()}))}renameWidgetPublishHistoryTitleRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.widgetId)throw new ue("widgetId",'Required parameter "widgetId" was null or undefined when calling renameWidgetPublishHistoryTitle().');if(null==e.version)throw new ue("version",'Required parameter "version" was null or undefined when calling renameWidgetPublishHistoryTitle().');if(null==e.renameWidgetPublishHistoryTitleRequest)throw new ue("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 pe(n,(e=>Zt(e)))}))}renameWidgetPublishHistoryTitle(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.renameWidgetPublishHistoryTitleRaw(e,t);return yield i.value()}))}setWidgetPublishHistoryLiveRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.widgetId)throw new ue("widgetId",'Required parameter "widgetId" was null or undefined when calling setWidgetPublishHistoryLive().');if(null==e.version)throw new ue("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 pe(n,(e=>si(e)))}))}setWidgetPublishHistoryLive(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.setWidgetPublishHistoryLiveRaw(e,t);return yield i.value()}))}updateWidgetRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling updateWidget().');if(null==e.updateWidgetRequest)throw new ue("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 me(n)}))}updateWidget(e,t){return Hi(this,void 0,void 0,(function*(){yield this.updateWidgetRaw(e,t)}))}updateWidgetRepositoryRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling updateWidgetRepository().');if(null==e.updateWidgetRepositoryRequest)throw new ue("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 pe(n,(e=>wi(e)))}))}updateWidgetRepository(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.updateWidgetRepositoryRaw(e,t);return yield i.value()}))}uploadWidgetThumbnailRaw(e,t){return Hi(this,void 0,void 0,(function*(){if(null==e.id)throw new ue("id",'Required parameter "id" was null or undefined when calling uploadWidgetThumbnail().');if(null==e.uploadWidgetThumbnailRequest)throw new ue("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 pe(n,(e=>Ii(e)))}))}uploadWidgetThumbnail(e,t){return Hi(this,void 0,void 0,(function*(){const i=yield this.uploadWidgetThumbnailRaw(e,t);return yield i.value()}))}}class Gi extends Error{constructor(e,t,i){super(e),this.code=t,this.statusCode=i,this.name="AuthError"}}class Xi{constructor(e={}){var t,i;this.currentToken=null,this.apiKey=null,this.refreshTimer=null,this.config=Object.assign({apiUrl:e.apiUrl||z(),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 re({basePath:this.config.apiUrl,apiKey:()=>t(this,void 0,void 0,(function*(){return e})),headers:{"X-SDK-Version":`embed-sdk/${_}`}});return new Ki(i)}createTokensApiForAccessToken(e){const i=new re({basePath:this.config.apiUrl,accessToken:()=>t(this,void 0,void 0,(function*(){return e})),headers:{"X-SDK-Version":`embed-sdk/${_}`}});return new Ki(i)}setApiKey(e){this.apiKey=e,this.currentToken={token:e,tokenType:"API-Key",expiresAt:null,scopes:[]},this.config.debug&&te.debug("AuthManager: API key set")}getValidToken(e){return t(this,void 0,void 0,(function*(){if(this.currentToken&&this.isTokenValid(this.currentToken)){if(Xi.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 Gi("No authentication method available","NO_AUTH_METHOD")}))}exchangeApiKeyForJWT(e){return t(this,void 0,void 0,(function*(){var t;if(!this.apiKey)throw new Gi("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 Gi("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&&te.info("AuthManager: Token exchanged successfully",{scopes:r.scopes,expiresAt:r.expiresAt}),r}catch(e){const t=e instanceof Gi?e:new Gi(`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(Xi.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)?(Xi.validatedTokens.add(this.currentToken.token),!0):(this.clearToken(),!1)}catch(e){return this.config.debug&&te.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&&Xi.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&&te.info("AuthManager: Token refreshed automatically")}catch(e){this.config.debug&&te.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&&te.debug("AuthManager: Disposed")}}Xi.validatedTokens=new Set;const Yi=P,Ji={};let Qi=null,Zi=null;const en={API_URL:q.PROD_API_URL,API_VERSION:q.VERSION,CLIENT_URL:q.PROD_CLIENT_URL,PRODUCTION_URL:q.PROD_CDN_URL,NODE_ENV:"production",ENABLE_EDITING:q.ENABLE_EDITING,API_KEY:Ji.PUBLIC_API_KEY,AXIOM_API_KEY:Ji.PUBLIC_AXIOM_API_KEY,STATSIG_KEY:Ji.PUBLIC_STATSIG_KEY};function tn(){return Zi||(Zi=new Xi({apiUrl:sn(),debug:hn.enabled})),Zi}function nn(){return t(this,void 0,void 0,(function*(){if(Zi&&Zi.hasAuthMethod())try{return yield Zi.getValidToken()}catch(e){}if(Qi)return yield Qi.getToken();const e=en.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 on(e){const t=(null==e?void 0:e.tokenProvider)||Qi;if(!t){const t=(null==e?void 0:e.apiKey)||en.API_KEY;return{apiKey:t,basePath:(null==e?void 0:e.basePath)||sn(),tokenProvider:t?new ie(t):void 0}}return{basePath:(null==e?void 0:e.basePath)||sn(),tokenProvider:t}}function sn(){return en.API_URL}function rn(){return en.PRODUCTION_URL}function an(){return`${sn()}${en.API_VERSION}`}const dn={isProduction:"production"===en.NODE_ENV,apiUrl:sn(),apiKey:en.API_KEY},ln={renderMode:j,displayMode:B,resize:$,width:N,height:F,autoscale:K},cn={customElements:H.CUSTOM_ELEMENTS,http3:H.HTTP3,resizeObserver:H.RESIZE_OBSERVER},un={batchSize:V,loadTimeout:G,retryAttempts:X},hn={enabled:L,logLevel:U},gn={AXIOM_API_KEY:en.AXIOM_API_KEY||"",AXIOM_DATASET:n,AXIOM_API_ENDPOINT:i,STATSIG_API_KEY:en.STATSIG_KEY||"",STATSIG_API_ENDPOINT:o,ENABLE_PERFORMANCE_TRACKING:s,PERFORMANCE_SAMPLE_RATE:r,PERFORMANCE_REPORTING_ENDPOINT:d,LCP_THRESHOLD:l,LCP_WARNING_THRESHOLD:c,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:k,MAX_METRICS_BUFFER:a},pn={ROOT_MARGIN:T,THRESHOLD:S,MAX_CONCURRENT:C,RETRY_ATTEMPTS:A,RETRY_DELAY:E},mn={MAX_PRELOAD_REQUESTS:R,PREFETCH_TIMEOUT:x,CACHE_DURATION:M,MAX_CONCURRENT_REQUESTS:W,DNS_PREFETCH_ENABLED:O,PRECONNECT_ENABLED:D},fn={DEBUG:L,LOG_LEVEL:U,VERSION:P};var vn=Object.freeze({__proto__:null,BROWSER_FEATURES:cn,DEBUG:hn,DEFAULT_WIDGET_CONFIG:ln,LAZY_LOADING_CONFIG:pn,PERFORMANCE:un,PERFORMANCE_CONFIG:gn,RESOURCE_CONFIG:mn,SDK_CONFIG:fn,VERSION:Yi,config:en,createSdkConfig:on,environment:dn,getApiUrl:sn,getAuthManager:tn,getAuthToken:nn,getCdnUrl:rn,getConfiguration:function(){return on()},getTokenProvider:function(){return Qi},getVersionedApiUrl:an,setApiKey:function(e){tn().setApiKey(e)},setTokenProvider:function(e){Qi=e}});class yn{constructor(){this.foundWidgets=[],this.scanStartTime=0}scan(){this.scanStartTime=performance.now();const e=["[data-composition-id]","[data-widget-id]","widgetic-widget","widgetic"],t=[];for(const i of e){const e=document.querySelectorAll(i);for(const i of Array.from(e))this.isValidWidget(i)&&t.push(i)}this.foundWidgets=t;const i=performance.now()-this.scanStartTime;return te.info(`FastScanner: Found ${t.length} widgets in ${i.toFixed(2)}ms`),t}isValidWidget(e){return e.hasAttribute("data-composition-id")||e.hasAttribute("data-widget-id")||e.hasAttribute("composition-id")}getScanTime(){return this.scanStartTime>0?performance.now()-this.scanStartTime:0}}class wn{constructor(){this.loadedChunks=new Set,this.loadingPromises=new Map,this.loadStartTime=0,this.loadStartTime=performance.now()}loadCoreChunks(){return t(this,void 0,void 0,(function*(){const e=[this.loadChunk("core",(()=>Promise.resolve().then((function(){return vn})))),this.loadChunk("scanner",(()=>Promise.resolve().then((function(){return eo})))),this.loadChunk("scanner",(()=>Promise.resolve().then((function(){return ao}))))];yield Promise.all(e),te.debug("ProgressiveLoader: Core chunks loaded")}))}loadRenderingChunks(){return t(this,void 0,void 0,(function*(){const e=[this.loadChunk("renderers",(()=>Promise.resolve().then((function(){return lr})))),this.loadChunk("renderers",(()=>Promise.resolve().then((function(){return Fs})))),this.loadChunk("renderers",(()=>Promise.resolve().then((function(){return sr}))))];yield Promise.all(e),te.debug("ProgressiveLoader: Rendering chunks loaded")}))}loadApiChunks(){return t(this,void 0,void 0,(function*(){const e=[this.loadChunk("api",(()=>Promise.resolve().then((function(){return go})))),this.loadChunk("api",(()=>Promise.resolve().then((function(){return yo}))))];yield Promise.all(e),te.debug("ProgressiveLoader: API chunks loaded")}))}loadFeatureChunk(e){return t(this,void 0,void 0,(function*(){switch(e){case"messaging":return this.loadChunk("messaging",(()=>Promise.resolve().then((function(){return Js}))));case"media":return this.loadChunk("media",(()=>Promise.resolve().then((function(){return qs}))));case"performance":return this.loadChunk("performance",(()=>Promise.resolve().then((function(){return mr}))));case"advanced":return this.loadChunk("advanced",(()=>Promise.resolve().then((function(){return Mr}))));case"security":return this.loadChunk("security",(()=>Promise.resolve().then((function(){return Ur}))));case"display":return this.loadChunk("display",(()=>Promise.resolve().then((function(){return qr}))));case"abTesting":return this.loadChunk("abTesting",(()=>Promise.resolve().then((function(){return la}))));default:return te.warn(`ProgressiveLoader: Unknown feature '${e}'`),null}}))}loadChunk(e,i){return t(this,void 0,void 0,(function*(){if(this.loadedChunks.has(e))return;if(this.loadingPromises.has(e))return this.loadingPromises.get(e);const t=i().then((t=>(this.loadedChunks.add(e),te.debug(`ProgressiveLoader: Loaded chunk '${e}'`),t))).catch((t=>{throw te.error(`ProgressiveLoader: Failed to load chunk '${e}'`,t),t}));return this.loadingPromises.set(e,t),t}))}getLoadedChunks(){return Array.from(this.loadedChunks)}getTotalLoadTime(){return performance.now()-this.loadStartTime}}class bn{constructor(e={}){this.scanner=new yn,this.loader=new wn,this.config=Object.assign({debug:!1,preloadCritical:!0,scanInterval:0,enableLazyLoading:!0},e),this.initStartTime=performance.now(),this.stats={scanTime:0,widgetsFound:0,chunksLoaded:[],totalLoadTime:0},this.config.debug&&(ee.setDebug(!0),ee.setLevel("debug"))}initialize(){return t(this,void 0,void 0,(function*(){try{te.info("WidgeticBootstrap: Starting fast initialization...");const e=this.scanner.scan();if(this.stats.widgetsFound=e.length,this.stats.scanTime=this.scanner.getScanTime(),0===e.length)return te.info("WidgeticBootstrap: No widgets found, minimal initialization"),this.finalizeStats(),this.stats;this.config.preloadCritical&&(yield this.loader.loadCoreChunks());const t=this.analyzeWidgetRequirements(e);let i=[];try{const{analyzeWidgetRequirementsEnhanced:t}=yield Promise.resolve().then((function(){return ha}));i=t(e)}catch(e){}const n=[...new Set([...t,...i])];return yield this.loadRequiredChunks(n),yield this.initializeFullSDK(e),this.finalizeStats(),te.info(`WidgeticBootstrap: Initialization complete in ${this.stats.totalLoadTime.toFixed(2)}ms`),this.stats}catch(e){throw te.error("WidgeticBootstrap: Initialization failed",e),e}}))}analyzeWidgetRequirements(e){const t=new Set;t.add("rendering"),t.add("api");for(const i of e){("widgetic-abtest"===i.tagName.toLowerCase()||i.hasAttribute("experiment-id")||i.hasAttribute("data-ab-test"))&&(t.add("abTesting"),t.add("messaging")),i.hasAttribute("data-interactive")&&t.add("messaging");const e=this.extractWidgetCapabilities(i);e.length>0&&e.forEach((e=>t.add(e)));const n=i.getAttribute("data-widget-id")||"",o=i.getAttribute("data-widget-type")||"";(n.includes("video")||n.includes("audio")||n.includes("media")||"media"===o)&&t.add("media"),(i.hasAttribute("data-editing")||"editing"===i.getAttribute("data-render-mode"))&&t.add("advanced");const s=i.getAttribute("data-display-mode");"overlay"!==s&&"popup"!==s&&"fullscreen"!==s||t.add("display"),(n.includes("form")||n.includes("input")||n.includes("contact")||"form"===o)&&t.add("security"),"gallery"!==o&&"interactive"!==o||t.add("messaging")}return te.debug("WidgeticBootstrap: Required features:",Array.from(t)),Array.from(t)}extractWidgetCapabilities(e){var t;const i=[];try{const n=e.getAttribute("data-widget-meta");if(n){const e=JSON.parse(n);(e.mediaCapabilities||e.supportsMedia)&&i.push("media"),(e.textCapabilities||e.supportsText||e.hasTextFields)&&i.push("security"),(e.supportsInteraction||e.hasInteractiveElements)&&i.push("messaging"),(e.supportsFullscreen||e.supportsOverlay)&&i.push("display"),(e.supportsABTesting||e.trackingCapabilities)&&i.push("abTesting")}const o=e.getAttribute("data-widget-type");if(o)switch(o){case"media":i.push("media");break;case"form":i.push("security","messaging");break;case"gallery":case"interactive":i.push("messaging")}if(e.matches("widgetic-widget[data-capabilities]")){const n=(null===(t=e.getAttribute("data-capabilities"))||void 0===t?void 0:t.split(","))||[];i.push(...n.map((e=>e.trim())))}}catch(e){te.debug("Failed to parse widget metadata, using fallback detection",{error:e})}return i}loadRequiredChunks(e){return t(this,void 0,void 0,(function*(){const t=[];for(const i of e)switch(i){case"rendering":t.push(this.loader.loadRenderingChunks());break;case"api":t.push(this.loader.loadApiChunks());break;default:t.push(this.loader.loadFeatureChunk(i))}yield Promise.all(t)}))}initializeFullSDK(e){return t(this,void 0,void 0,(function*(){var t;const{getSDK:i}=yield Promise.resolve().then((function(){return Pd})),n=i({debug:this.config.debug,lazyLoading:{enabled:null===(t=this.config.enableLazyLoading)||void 0===t||t,config:{}}});yield n.init(),te.info(`WidgeticBootstrap: Processing ${e.length} widgets through full SDK`)}))}finalizeStats(){this.stats.totalLoadTime=performance.now()-this.initStartTime,this.stats.chunksLoaded=this.loader.getLoadedChunks()}getStats(){return Object.assign({},this.stats)}}let In=null;function kn(e){return t(this,void 0,void 0,(function*(){return In?(te.warn("WidgeticBootstrap: Already initialized"),In.getStats()):(In=new bn(e),yield In.initialize())}))}function Tn(){return(null==In?void 0:In.getStats())||null}if("undefined"!=typeof document){const e=()=>{window.__WIDGETIC_SDK_INITIALIZED__||kn({debug:"development"===en.NODE_ENV,preloadCritical:!0}).catch((e=>{te.error("WidgeticBootstrap: Auto-initialization failed",e)}))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}"undefined"!=typeof window&&(window.WidgeticBootstrap={init:kn,getStats:Tn,version:"1.0.0"});const Sn=2147483647;function Cn(e){const t=e.getAttribute("composition-id");if(!t)throw new Error("Missing required composition-id attribute");return{compositionId:t,renderMode:An(e.getAttribute("render-mode")),displayMode:En(e.getAttribute("display-mode")),resize:Rn(e.getAttribute("resize")),width:parseInt(e.getAttribute("width")||"")||ln.width,height:parseInt(e.getAttribute("height")||"")||ln.height,autoscale:Nn(e),adaptive:xn(e.getAttribute("adaptive")),responsive:Mn(e.getAttribute("responsive")),device:Zn(e),fullscreen:Wn(e),triggers:Xn(e),overlay:Dn(e),popup:Bn(e),media:Vn(e),content:Gn(e)}}function An(e){switch(e){case"iframe":case"custom-element":return e;default:return"auto"}}function En(e){switch(e){case"overlay":case"popup":case"fullscreen":case"modal":return e;default:return"inline"}}function Rn(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 xn(e){if(!e)return;const t=parseInt(e);return isNaN(t)?void 0:t}function Mn(e){if(!e)return;const t=parseInt(e);return isNaN(t)?void 0:t}function Wn(e){if("enabled"===e.getAttribute("fullscreen")||"true"===e.getAttribute("fullscreen-enabled"))return{enabled:!0,trigger:On(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 On(e){switch(e){case"click":case"double-click":case"hover":case"auto":case"manual":return e;default:return"click"}}function Dn(e){if("enabled"===e.getAttribute("overlay")||"true"===e.getAttribute("overlay-enabled"))return{enabled:!0,position:qn(e.getAttribute("overlay-position")),backdrop:Un(e),background:Pn(e,Un(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:_n(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:zn(e.getAttribute("overlay-animation")),overlayWidth:e.getAttribute("overlay-width")||void 0,overlayHeight:e.getAttribute("overlay-height")||void 0,overlayResize:jn(e.getAttribute("overlay-resize-mode")),keepDimensions:"false"!==e.getAttribute("keep-dimensions"),embedTarget:e.getAttribute("embed-target")||void 0}}function Ln(e){return"true"===e.getAttribute("overlay-backdrop")}function Un(e){return"false"!==e.getAttribute("overlay-backdrop")}function Pn(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 _n(e){switch(e){case"click":case"hover":case"manual":case"auto":return e;default:return"click"}}function zn(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 qn(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 jn(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 Bn(e){if("enabled"===e.getAttribute("popup")||"true"===e.getAttribute("popup-enabled"))return{enabled:!0,trigger:$n(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 $n(e){switch(e){case"click":case"manual":return e;default:return"click"}}function Nn(e){const t=e.getAttribute("autoscale");return!!t&&(("true"===t||""===t||"false"!==t)&&(Fn(e)||!0))}function Fn(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 Kn(e){return`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function Hn(e){return"widgetic"===e.tagName.toLowerCase()&&e.hasAttribute("composition-id")}function Vn(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 l=e.getAttribute("media-global-volume")||e.getAttribute("data-media-global-volume");return null!==l&&(t.globalVolume="true"===l||""===l),t}function Gn(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 Xn(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:Jn(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:Yn(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:jn(e.getAttribute("overlay-resize-mode")),backdrop:Ln(e),background:Pn(e,Ln(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 Yn(e){const t=parseInt(e.getAttribute("overlay-z-index")||"");if(Number.isFinite(t)&&!(t<=0))return Math.min(t,Sn)}function Jn(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 Zn(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}}var eo=Object.freeze({__proto__:null,generateInstanceId:Kn,isValidWidgetElement:Hn,parseTriggerConfig:Xn,parseWidgetConfig:Cn});function to(){return"undefined"==typeof window?{customElements:!1,http3:!1,resizeObserver:!1,fullscreenApi:!1,popupBlocking:!1}:{customElements:"undefined"!=typeof customElements&&"function"==typeof customElements.define,http3:io(),resizeObserver:"undefined"!=typeof ResizeObserver,fullscreenApi:no(),popupBlocking:oo()}}function io(){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 no(){return!("undefined"==typeof document||!document.documentElement)&&!!(document.documentElement.requestFullscreen||document.documentElement.webkitRequestFullscreen||document.documentElement.mozRequestFullScreen||document.documentElement.msRequestFullscreen)}function oo(){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 so(e,t){switch(e){case"custom-element":case"auto":default:return t.customElements?"custom-element":"iframe";case"iframe":return"iframe"}}function ro(){if("undefined"==typeof localStorage)return!1;try{const e="widgetic-test";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}}var ao=Object.freeze({__proto__:null,checkSdkInitialization:function(){if("undefined"==typeof window)return!1;const e="widgetic-sdk-initialized";return ro()?!!localStorage.getItem(e)||(localStorage.setItem(e,Date.now().toString()),!1):!!window.__widgeticInitialized},clearSdkInitialization:function(){ro()&&localStorage.removeItem("widgetic-sdk-initialized"),delete window.__widgeticInitialized},detectBrowserCapabilities:to,determineBestRenderMode:so,hasIntersectionObserver:function(){return"undefined"!=typeof IntersectionObserver},isLocalStorageAvailable:ro});const lo={maxBatchSize:50,debounceDelay:10,retryAttempts:3,retryBaseDelay:1e3,cacheTTL:3e5};class co{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({},lo),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 nn(),o=new re({basePath:an(),apiKey:()=>t(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${Yi}`}}),s=new Ni(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 nn(),o=new re({basePath:an(),apiKey:()=>t(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${Yi}`}}),s=new Vi(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 uo=null;function ho(){return uo||(uo=new co),uo}var go=Object.freeze({__proto__:null,BatchApiClient:co,getBatchClient:ho,resetBatchClient:function(){uo=null}});const po={cacheTTL:18e5,loadTimeout:1e4,maxRetries:3,retryDelay:1e3,enableHttp3:!0,cdnBaseUrl:rn()};class mo{constructor(e={}){this.moduleCache=new Map,this.loadingPromises=new Map,this.dependencyGraph=new Map,this.http3Supported=null,this.config=Object.assign(Object.assign({},po),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 fo=null;function vo(){return fo||(fo=new mo),fo}var yo=Object.freeze({__proto__:null,ModuleLoader:mo,getModuleLoader:vo,resetModuleLoader:function(){fo=null}});const wo=["DOMAIN_NOT_ALLOWED","UNPUBLISHED","SUSPENDED","NOT_FOUND","RATE_LIMITED"],bo={DOMAIN_NOT_ALLOWED:"domain_not_allowed",UNPUBLISHED:"unpublished",SUSPENDED:"suspended",NOT_FOUND:"not_found",RATE_LIMITED:"rate_limited"};function Io(e){return wo.includes(e)?bo[e]:null}const ko=/^https:\/\/[^\s"'<>]+\.(?:png|jpe?g|webp|gif|avif)(?:\?[^\s"'<>]*)?$/i,To=new Set;function So(e,t,i=e=>e){if("undefined"!=typeof document&&document.head)try{for(const n of function(e,t,i=2){const n=[];let o=0;const s=(e,t)=>{if(n.length>=i||o>=400)return;if(o+=1,"string"==typeof e)return void(ko.test(e)&&!n.includes(e)&&n.push(e));if(t>=4||null===e||"object"!=typeof e)return;const r=Array.isArray(e)?e:Object.values(e);for(const e of r)s(e,t+1)};return s(e,0),s(t,0),n}(e,t)){const e=i(n);if(To.has(e))continue;To.add(e);const t=document.createElement("link");t.setAttribute("rel","preload"),t.setAttribute("as","image"),t.setAttribute("href",e),document.head.appendChild(t)}}catch(e){}}const Co=[480,960,1600],Ao=["static.widgetic.com","cdn.widgetic.com"],Eo=/^https:\/\/[^\s"'<>]+\.(?:png|jpe?g|webp|avif)(?:\?[^\s"'<>]*)?$/i;function Ro(){var e;if("undefined"==typeof window)return Co[Co.length-1];return function(e){var t;const i=Co,n=Number.isFinite(e)&&e>0?e:i[i.length-1];return null!==(t=i.find((e=>e>=n)))&&void 0!==t?t:i[i.length-1]}((window.innerWidth||(null===(e=document.documentElement)||void 0===e?void 0:e.clientWidth)||0)*Math.min(window.devicePixelRatio||1,2))}function xo(e,t){let i=0;const n=(e,o)=>{if(i+=1,i>5e3)return e;if("string"==typeof e)return function(e,t){if(!Eo.test(e))return e;let i;try{i=new URL(e)}catch(t){return e}if(!Ao.includes(i.hostname.toLowerCase()))return e;if(i.pathname.startsWith("/cdn-cgi/"))return e;const n=`width=${t},fit=scale-down,quality=80,format=auto`;return`${i.origin}/cdn-cgi/image/${n}/${e}`}(e,t);if(o>=8||null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map((e=>n(e,o+1)));const s={};for(const[t,i]of Object.entries(e))s[t]=n(i,o+1);return s};return n(e,0)}function Mo(e,t,i){try{if(!function(e){if(!e||!0!==e.optimize)return!1;if("undefined"==typeof window||"undefined"==typeof document)return!1;if(!1===window.WIDGETIC_IMAGE_OPTIMIZE)return!1;const t=document.querySelectorAll("script[src*='embed-sdk'][data-image-optimize]");for(const e of Array.from(t))if("off"===(e.getAttribute("data-image-optimize")||"").trim().toLowerCase())return!1;return!0}(e))return{content:t,contentItems:i};const n=Ro();return{content:xo(t,n),contentItems:xo(i,n)}}catch(e){return{content:t,contentItems:i}}}const Wo="lookups",Oo=864e5;function Do(){if("undefined"==typeof window||"undefined"==typeof document)return!1;const e=window;if(!e.indexedDB)return!1;if(!1===e.WIDGETIC_EMBED_LOOKUP_CACHE)return!1;const t=document.querySelectorAll("script[src*='embed-sdk'][data-lookup-cache]");for(const e of Array.from(t))if("off"===(e.getAttribute("data-lookup-cache")||"").trim().toLowerCase())return!1;return!0}let Lo=null;function Uo(){return Lo||(Lo=new Promise((e=>{try{const i=window.indexedDB.open("widgetic-embed-lookup",1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Wo)||i.result.createObjectStore(Wo)},i.onsuccess=()=>{e(i.result),function(e){t(this,void 0,void 0,(function*(){try{const t=e.transaction(Wo,"readwrite"),i=t.objectStore(Wo).openCursor(),n=Date.now()-Oo;i.onsuccess=()=>{const e=i.result;if(!e)return;const t=e.value;(!t||"number"!=typeof t.storedAtMs||t.storedAtMs<n)&&e.delete(),e.continue()}}catch(e){}}))}(i.result)},i.onerror=()=>e(null),i.onblocked=()=>e(null)}catch(t){e(null)}})),Lo)}const Po="https://cdn.widgetic.com",_o="DOMAIN_NOT_ALLOWED";function zo(){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 qo(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 jo(e,t){if(!e||"object"!=typeof e)return null;let i="string"==typeof e.embedUrl?e.embedUrl:"";if(!i&&"string"==typeof e.js_path&&e.js_path.trim()){const t=e.js_path.trim();i=/^https?:\/\//i.test(t)?t:`${Po}${t.startsWith("/")?"":"/"}${t}`}else!i&&"string"==typeof e.embed_url&&e.embed_url.trim()&&(i=e.embed_url.trim());if(!i)return null;const n=function(e){if(!e||"object"!=typeof e)return;const t=e;return"string"!=typeof t.moduleUrl||"number"!=typeof t.contractVersion?void 0:{moduleUrl:t.moduleUrl,contractVersion:t.contractVersion,moduleHash:"string"==typeof t.moduleHash?t.moduleHash:null}}(e.direct),o="string"==typeof e.compositionId?e.compositionId:void 0,s="string"==typeof e.widgetId?e.widgetId:"string"==typeof e.id?e.id:void 0,r="string"==typeof e.entryWriteToken?e.entryWriteToken:void 0;let a;if(e.entries&&"object"==typeof e.entries){const t=e.entries;"string"==typeof t.url&&(a=Object.assign({url:t.url},"string"==typeof t.writeToken?{writeToken:t.writeToken}:r?{writeToken:r}:{}))}else r&&o&&t&&(a={url:`${t.replace(/\/+$/,"")}/embed/compositions/${o}/entries`,writeToken:r});const d=e.media,l=d&&"object"==typeof d&&"boolean"==typeof d.optimize?{optimize:d.optimize}:void 0,c=Mo(l,e.content&&"object"==typeof e.content?e.content:{},Array.isArray(e.contentItems)?e.contentItems:[]);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({embedUrl:i,compositionId:o},s?{widgetId:s}:{}),{design:e.design&&"object"==typeof e.design?e.design:{},content:c.content,contentItems:c.contentItems}),l?{media:l}:{}),n?{direct:n}:{}),r?{entryWriteToken:r}:{}),a?{entries:a}:{})}function Bo(e){return t(this,void 0,void 0,(function*(){let t=null;try{t=yield e.json()}catch(e){t=null}const i=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;const t=e.code;return"string"==typeof t&&t.length>0&&t.length<=64?t:null}(t),n=(i&&Io(i)?i:null)||(429===(o=e.status)?"RATE_LIMITED":404===o?"NOT_FOUND":null);var o;if(!n)return null;const s=Io(n);return s?{gatewayCode:n,stateCode:s}:null}))}const $o=new Map;function No(e){try{return new URL(e).origin}catch(e){return""}}function Fo(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!==_o)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:_o,reason:n}}catch(e){return null}}))}(i);if(e)return{kind:"refused",refusal:e};const n=yield Bo(i);return n?{kind:"failed",failure:n}:{kind:"unavailable"}}return{kind:"json",json:yield i.json()}}catch(e){return{kind:"unavailable"}}}))}function Ko(e){const i=$o.get(e);if(i)return i;const n=Fo(e).then((i=>("json"===i.kind&&jo(i.json,No(e))&&function(e,i){t(this,void 0,void 0,(function*(){if(!Do())return;const t=yield Uo();if(t)try{const n={json:i,storedAtMs:Date.now()};t.transaction(Wo,"readwrite").objectStore(Wo).put(n,e)}catch(e){}}))}(e,i.json),i)));return $o.set(e,n),n.finally((()=>{$o.get(e)===n&&$o.delete(e)})),n}function Ho(e){return JSON.parse(JSON.stringify(e))}function Vo(e){return t(this,void 0,void 0,(function*(){const i=No(e),n=yield function(e){return t(this,void 0,void 0,(function*(){if(!Do())return null;const t=yield Uo();return t?new Promise((i=>{try{const n=t.transaction(Wo,"readonly").objectStore(Wo).get(e);n.onsuccess=()=>{const e=n.result,t=e&&"number"==typeof e.storedAtMs&&e.json&&"object"==typeof e.json;i(t?e:null)},n.onerror=()=>i(null)}catch(e){i(null)}})):null}))}(e);if(n&&function(e,t=Date.now()){const i=t-e.storedAtMs;return i>=0&&i<=3e4}(n)){const t=jo(Ho(n.json),i);if(t)return Ko(e),So(t.content,t.contentItems),{kind:"payload",payload:t,gatewayOrigin:i}}const o=yield Ko(e);if("json"!==o.kind)return o;const s=jo(Ho(o.json),i);return s?(So(s.content,s.contentItems),{kind:"payload",payload:s,gatewayOrigin:i}):{kind:"unavailable"}}))}function Go(e){return"refused"===e.kind?{status:"refused",refusal:e.refusal}:"failed"===e.kind?{status:"failed",failure:e.failure}:{status:"found",payload:e.payload,gatewayOrigin:e.gatewayOrigin||void 0}}function Xo(){const e=[...zo()];e.push(sn().replace(/\/+$/,""));const t=String(q.PROD_API_URL).replace(/\/+$/,"");return t&&e.push(t),[...new Set(e)]}function Yo(e){const t=`/embed/compositions/${e}`;return Xo().map((e=>`${e}${t}`))}function Jo(e){return t(this,void 0,void 0,(function*(){const t=zo();for(const i of t){const t=yield Vo(`${i}/embed/compositions/${e}`);if("unavailable"!==t.kind)return Go(t)}const i=yield function(e){const t=qo(e);return t?Promise.resolve(t):"undefined"==typeof document?Promise.resolve(null):new Promise((t=>{const i=document.createElement("script");i.src=`${Po}/embed/compositions/${e}.js`,i.async=!0,i.onload=()=>t(qo(e)),i.onerror=()=>t(null),document.head.appendChild(i)}))}(e);if(i){for(const t of Yo(e)){const e=yield Vo(t);if("refused"===e.kind)return Go(e);if("failed"!==e.kind&&"payload"===e.kind){const t=e.payload;return{status:"found",payload:Object.assign(Object.assign({},t),{embedUrl:t.embedUrl||i}),gatewayOrigin:e.gatewayOrigin||void 0}}}return{status:"found",payload:{embedUrl:i,compositionId:e}}}let n=null;for(const t of Yo(e)){const e=yield Vo(t);if("refused"===e.kind)return Go(e);if("failed"!==e.kind){if("payload"===e.kind)return Go(e)}else n=e.failure}return n?{status:"failed",failure:n}:{status:"not-found"}}))}function Qo(e){return t(this,void 0,void 0,(function*(){const t=zo();for(const i of t){const t=yield Vo(`${i}/widgets/${encodeURIComponent(e)}`);if("unavailable"!==t.kind)return Go(t)}const i=qo(e);let n=null;for(const t of function(e){const t=`/widgets/${encodeURIComponent(e)}`;return Xo().map((e=>`${e}${t}`))}(e)){const e=yield Vo(t);if("refused"===e.kind)return Go(e);if("failed"!==e.kind){if("payload"===e.kind)return Go(e)}else n=e.failure}return i?{status:"found",payload:{embedUrl:i,widgetId:e}}:n?{status:"failed",failure:n}:{status:"not-found"}}))}const Zo=new Set;function es(e,t){var i;if(Zo.has(e))return;Zo.add(e);"undefined"!=typeof window&&(null===(i=window.location)||void 0===i?void 0:i.hostname)&&window.location.hostname,t.reason&&t.reason}function ts(e,t,i,n,o){const s=document.createElement("iframe");return s.src=e,s.width=t,s.height=i,s.setAttribute("frameborder","0"),s.setAttribute("allowfullscreen",""),s.style.border="0",s.style.display="block",s.style.maxWidth="100%",n&&s.setAttribute("data-composition-id",n),function(e,t){if(!t)return;const i=t.design&&Object.keys(t.design).length>0?t.design:null,n=t.content&&Object.keys(t.content).length>0?t.content:null,o=t.contentItems&&t.contentItems.length>0?t.contentItems:null;if(!i&&!n&&!o)return;const s=()=>{const t=e.contentWindow;if(!t)return;const s={type:"widgetic:update"};i&&(s.design=i),n&&(s.content=n),o&&(s.contentItems=o),t.postMessage(s,"*")};window.addEventListener("message",(t=>{t.source===e.contentWindow&&"widgetic:ready"===(t.data&&t.data.type||"")&&s()})),e.addEventListener("load",(()=>{s(),window.setTimeout(s,80),window.setTimeout(s,400)}))}(s,o),s}const is=new Set(["id","class","style","title","lang","dir","hidden","tabindex","role","slot","part","draggable","contenteditable","spellcheck","translate","composition-id","compositionid","composition","widget","widget-id","widgetid","src","width","height","resize","resize-mode","render-mode","display-mode","autoscale","workflow-id","autoscale-min-height","autoscale-max-height","autoscale-debounce","autoscale-threshold","autoscale-animate","autoscale-animation-duration","adaptive","responsive","theme","mode","colors","context","values","media-resolver","mediaresolver","sandbox","autoload","use-iframe","embed-target","event-trigger","trigger-delay","trigger-scroll-distance","overlay-position","overlay-full-width","overlay-backdrop","max-views","time-period","device-mobile-enabled","device-desktop-enabled","display-on-mobile","display-on-desktop","use-breakpoints","mobile-breakpoint","tablet-breakpoint","desktop-breakpoint","design","content","items","content-items","contentitems"]),ns={backgroundcolor:"backgroundColor",textcolor:"textColor",primarycolor:"primaryColor",secondarycolor:"secondaryColor",accentcolor:"accentColor",bordercolor:"borderColor",borderradius:"borderRadius",borderwidth:"borderWidth",fontsize:"fontSize",fontfamily:"fontFamily",fontweight:"fontWeight",lineheight:"lineHeight",letterspacing:"letterSpacing"},os=new WeakMap;function ss(e){const t=e.trim().replace(/^data-/,"").replace(/-([a-zA-Z0-9])/g,((e,t)=>t.toUpperCase())),i=t.toLowerCase();return t===i&&ns[i]?ns[i]:t}function rs(e){var t,i,n,o,s,r,a,d;const l=(null===(t=e.getAttribute("composition-id"))||void 0===t?void 0:t.trim())||(null===(i=e.getAttribute("compositionid"))||void 0===i?void 0:i.trim())||(null===(n=e.getAttribute("data-composition-id"))||void 0===n?void 0:n.trim())||(null===(o=e.getAttribute("composition"))||void 0===o?void 0:o.trim());if(l)return{kind:"composition",id:l};const c=(null===(s=e.getAttribute("widget"))||void 0===s?void 0:s.trim())||(null===(r=e.getAttribute("widget-id"))||void 0===r?void 0:r.trim())||(null===(a=e.getAttribute("widgetid"))||void 0===a?void 0:a.trim())||(null===(d=e.getAttribute("data-widget-id"))||void 0===d?void 0:d.trim());return c?{kind:"widget",id:c}:null}const as=new WeakSet;function ds(e){if(!e||as.has(e))return;as.add(e);const t=[{prop:"values",attr:"values"},{prop:"context",attr:"context"},{prop:"design",attr:"design"},{prop:"content",attr:"content"},{prop:"contentItems",attr:"content-items"}];for(const{prop:i,attr:n}of t){const t=Object.prototype.hasOwnProperty.call(e,i),o=t?e[i]:void 0;t&&delete e[i];const s=t=>{if(null==t||""===t)e.removeAttribute(n);else if("string"==typeof t)e.getAttribute(n)!==t&&e.setAttribute(n,t);else if("object"==typeof t)try{const i=JSON.stringify(t);e.getAttribute(n)!==i&&e.setAttribute(n,i)}catch(e){}};try{Object.defineProperty(e,i,{configurable:!0,enumerable:!1,get:()=>e.getAttribute(n),set(e){s(e)}}),t&&void 0!==o&&s(o)}catch(e){}}const i=[{prop:"mediaResolver",attr:"media-resolver"},{prop:"compositionId",attr:"composition-id"},{prop:"widgetId",attr:"widget-id"}];for(const{prop:t,attr:n}of i){const i=Object.prototype.hasOwnProperty.call(e,t),o=i?e[t]:void 0;i&&delete e[t];const s=t=>{if(null==t||""===t)e.removeAttribute(n);else{const i=String(t);e.getAttribute(n)!==i&&e.setAttribute(n,i)}};try{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get:()=>e.getAttribute(n),set(e){s(e)}}),i&&void 0!==o&&s(o)}catch(e){}}}function ls(e){const t=rs(e);return t?t.id:null}function cs(e){if("SCRIPT"!==e.tagName.toUpperCase())return!1;const t=(e.getAttribute("type")||"").trim().toLowerCase();return"application/json"===t||"application/ld+json"===t||"application/widgetic+json"===t||(e.hasAttribute("data-widgetic-json")||e.hasAttribute("data-widgetic-config"))}function us(e){const t=e.tagName.toUpperCase();return"SCRIPT"===t?!cs(e):"IFRAME"===t||"STYLE"===t||"TEMPLATE"===t||!!(e.hasAttribute("data-widgetic-direct")||e.hasAttribute("data-widgetic-internal")||e.classList.contains("widgetic-direct-target"))}function hs(e){return Array.from(e.children).filter((e=>!us(e)))}function gs(e){const t=e.toLowerCase();return!!is.has(t)||(!!t.startsWith("data-widgetic-")||(!!t.startsWith("aria-")||!!t.startsWith("on")))}function ps(e){const t=e.trim();if("true"===t)return!0;if("false"===t)return!1;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch(t){return e}return e}function ms(e){if(!e||!e.trim())return null;try{const t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch(e){}return null}function fs(e){return e.filter((e=>Boolean(e&&"object"==typeof e&&!Array.isArray(e)))).map(((e,t)=>function(e,t){const i={};for(const[t,n]of Object.entries(e))"properties"===t||"inputController"===t||t in Object.prototype||(i[t]=n);if(Array.isArray(e.properties))for(const t of e.properties){if(!t||"object"!=typeof t||Array.isArray(t))continue;const e=t,n="string"==typeof e.name?e.name.trim():"";if(!n||n in Object.prototype)continue;const o=void 0!==e.value&&null!==e.value?e.value:e.defaultValue;void 0!==o&&(i[n]=o)}const n="string"==typeof i.id&&i.id.trim()?i.id:"string"==typeof e.id&&e.id.trim()?e.id:`item-${t+1}`;return Object.assign(Object.assign({id:n,order:t+1},i),{metadata:Object.assign({service:"declarative"},i)})}(e,t)))}function vs(e){if(!e||!e.trim())return null;try{const t=JSON.parse(e);if(Array.isArray(t))return fs(t)}catch(e){}return null}function ys(e,t,i=!1){if(Array.isArray(e)){let n=!1;for(const o of e){if(!o||"object"!=typeof o||Array.isArray(o))continue;const e=o,s="string"==typeof e.name?e.name.trim():"";if(!s||s in Object.prototype)continue;const r=void 0!==e.value&&null!==e.value?e.value:e.defaultValue;null!=r&&(t[s]=i?"string"==typeof r?r:String(r):r,n=!0)}return n}if(e&&"object"==typeof e&&!Array.isArray(e)){let n=!1;for(const[o,s]of Object.entries(e))if(o&&!(o in Object.prototype)&&s&&"object"==typeof s&&!Array.isArray(s)){const e=s;if("defaultValue"in e||"value"in e||"inputController"in e){const s=void 0!==e.value&&null!==e.value?e.value:e.defaultValue;null!=s&&(t[o]=i?"string"==typeof s?s:String(s):s,n=!0);continue}}return n}return!1}function ws(e,t){const i={};let n=!1;if(Array.isArray(e.componentGroups)){n=!0;for(const t of e.componentGroups){if(!t||"object"!=typeof t)continue;const e=t.components;if(Array.isArray(e))for(const t of e){if(!t||"object"!=typeof t)continue;const e=t;if(Array.isArray(e.propertyGroups))for(const t of e.propertyGroups)t&&"object"==typeof t&&ys(t.properties,i,!0);e.properties&&ys(e.properties,i,!0)}}}if(Array.isArray(e.propertyGroups)){n=!0;for(const t of e.propertyGroups)t&&"object"==typeof t&&ys(t.properties,i,!0)}if(e.properties&&ys(e.properties,i,!0)&&(n=!0),n)for(const[e,n]of Object.entries(i))t[e]=String(n);else for(const[i,n]of Object.entries(e))i in Object.prototype||null==n||(t[i]="string"==typeof n?n:JSON.stringify(n))}const bs=new Set(["$schema","id","name","version","contentType","genericContent","contentItems","contentItemsSnapshot","items","options","componentGroups","propertyGroups"]);function Is(e,t){let i=null,n=!1;if(e.genericContent&&"object"==typeof e.genericContent&&!Array.isArray(e.genericContent)){n=!0;const i=e.genericContent;if(!ys(i.properties,t,!1))for(const[e,n]of Object.entries(i))"properties"===e||"inputController"===e||e in Object.prototype||void 0===n||(t[e]=n)}e.properties&&ys(e.properties,t,!1)&&(n=!0);const o=Array.isArray(e.contentItems)?e.contentItems:Array.isArray(e.items)?e.items:Array.isArray(e.contentItemsSnapshot)?e.contentItemsSnapshot:null;o&&(i=fs(o));for(const[i,s]of Object.entries(e))i in Object.prototype||void 0===s||"contentItems"!==i&&"items"!==i&&"contentItemsSnapshot"!==i&&"genericContent"!==i&&"design"!==i&&"content"!==i&&"values"!==i&&(n&&(bs.has(i)||"properties"===i)||(!o||"options"!==i&&"contentType"!==i&&"$schema"!==i)&&(t[i]=s));return i}function ks(e){var t;const i=Array.from(e.children).filter((e=>!us(e)&&!cs(e)));if(0===i.length)return e.querySelector("[data-widgetic-direct], iframe")||Array.from(e.children).some(cs)?(os.delete(e),[]):null!==(t=os.get(e))&&void 0!==t?t:[];const n=i.map(((e,t)=>{var i;e.hasAttribute("data-widgetic-item")||(e.setAttribute("data-widgetic-item","1"),e instanceof HTMLElement&&(e.hidden=!0,e.style.display="none"));const n={};for(const t of Array.from(e.attributes)){const e=t.name.toLowerCase();if("data-widgetic-item"===e||"hidden"===e)continue;if("style"===e&&"display:none;"===t.value.replace(/\s+/g,""))continue;const i=ss(t.name);i&&!(i in Object.prototype)&&(n[i]=ps(t.value))}if(0===e.children.length){const t=null===(i=e.textContent)||void 0===i?void 0:i.trim();t&&(void 0===n.content&&(n.content=t),void 0===n.text&&(n.text=t))}const o="string"==typeof n.id&&n.id.trim()?n.id:`item-${t+1}`;return Object.assign(Object.assign({id:o,order:t+1},n),{metadata:Object.assign({service:"declarative"},n)})}));return os.set(e,n),n}function Ts(e,t){if(!e)return null;if(t in e)return t;const i=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===i)return t;return null}function Ss(e,t){const i=function(e,t){var i;const n={},o={};let s=[];const r=Array.from(e.children).filter(cs);for(const e of r){const r=null===(i=e.textContent)||void 0===i?void 0:i.trim();if(!r)continue;let a;try{a=JSON.parse(r)}catch(e){continue}if(Array.isArray(a)){s=fs(a);continue}if(!a||"object"!=typeof a)continue;const d=a,l=(e.getAttribute("data-schema")||e.getAttribute("data-widgetic-json")||e.getAttribute("data-widgetic-config")||"").trim().toLowerCase();if("design"===l){ws(d,n);continue}if("content"===l){const e=Is(d,o);e&&e.length>0&&(s=e);continue}let c=!1;if(d.design&&"object"==typeof d.design&&!Array.isArray(d.design)&&(ws(d.design,n),c=!0),(Array.isArray(d.componentGroups)||Array.isArray(d.propertyGroups))&&(ws(d,n),c=!0),d.content&&"object"==typeof d.content&&!Array.isArray(d.content)){const e=Is(d.content,o);e&&e.length>0&&(s=e),c=!0}if(d.values&&"object"==typeof d.values&&!Array.isArray(d.values)){const e=Is(d.values,o);e&&e.length>0&&(s=e),c=!0}if(d.genericContent||Array.isArray(d.contentItems)||Array.isArray(d.items)||Array.isArray(d.contentItemsSnapshot)){const e=Is(d,o);e&&e.length>0&&(s=e),c=!0}if(!c)for(const[e,i]of Object.entries(d)){if(e in Object.prototype||null==i)continue;const s=Ts(null==t?void 0:t.content,e),r=Ts(null==t?void 0:t.design,e);r&&!s?n[r]="string"==typeof i?i:JSON.stringify(i):s&&!r?o[s]=i:(o[e]=i,"string"!=typeof i&&"number"!=typeof i||(n[e]=String(i)))}}return{design:n,content:o,contentItems:s}}(e,t),n=Object.assign({},i.design),o=Object.assign({},i.content);let s=null;const r=ms(e.getAttribute("design"));r&&ws(r,n);const a=ms(e.getAttribute("content"));if(a){const e=Is(a,o);e&&e.length>0&&(s=e)}const d=ms(e.getAttribute("values"));if(d){const e=Is(d,o);e&&e.length>0&&(s=e)}for(const i of Array.from(e.attributes)){const e=i.name,s=e.toLowerCase();if(s.startsWith("design-")&&s.length>7){const o=ss(e.slice(7));if(o&&!(o in Object.prototype)){n[Ts(null==t?void 0:t.design,o)||o]=i.value}continue}if(s.startsWith("content-")&&"content-items"!==s&&s.length>8){const n=ss(e.slice(8));if(n&&!(n in Object.prototype)){o[Ts(null==t?void 0:t.content,n)||n]=ps(i.value)}continue}if(gs(e))continue;const r=ss(e);if(!r||r in Object.prototype)continue;const a=Ts(null==t?void 0:t.content,r),d=Ts(null==t?void 0:t.design,r);if(a&&!d)o[a]=ps(i.value);else if(d&&!a)n[d]=i.value;else{n[r]=i.value,o[r]=ps(i.value);const t=e.replace(/^data-/,"");t===r||t in Object.prototype||(n[t]=i.value)}}let l=ks(e);if(0===l.length){const t=vs(e.getAttribute("content-items"))||vs(e.getAttribute("contentitems"))||vs(e.getAttribute("items"))||s;t&&t.length>0?l=t:i.contentItems.length>0&&(l=i.contentItems)}return{design:n,content:o,contentItems:l,hasOverrides:Object.keys(n).length>0||Object.keys(o).length>0||l.length>0}}function Cs(e,t){const i=null!=t?t:{},n=Ss(e,i);return n.hasOverrides?Object.assign(Object.assign({},i),{design:Object.assign(Object.assign({},i.design||{}),n.design),content:Object.assign(Object.assign({},i.content||{}),n.content),contentItems:n.contentItems.length>0?n.contentItems:i.contentItems||[]}):i}function As(e){var t,i;if(0===e.length)return!0;for(const n of e){if("attributes"===n.type){const e=(null===(t=n.attributeName)||void 0===t?void 0:t.toLowerCase())||"";if(!e)continue;if("data-widgetic-mounted"===e||"data-widgetic-mounting"===e||"data-widgetic-refused"===e||"data-widgetic-context-invalid"===e||"data-widgetic-overlay"===e||"data-device-restricted"===e||"data-widgetic-item"===e||"hidden"===e)continue;if("style"===e&&n.target!==(null===(i=n.target.ownerDocument)||void 0===i?void 0:i.body)&&n.target instanceof Element&&n.target.hasAttribute("data-widgetic-item"))continue;if(n.target instanceof Element&&us(n.target))continue;return!0}if("childList"===n.type){if(n.target instanceof Element&&us(n.target))continue;if([...Array.from(n.addedNodes),...Array.from(n.removedNodes)].some((e=>!(e instanceof Element&&us(e)))))return!0}if("characterData"===n.type){const e=n.target.parentElement;if(e&&!us(e))return!0}}return!1}const Es=new WeakMap;const Rs="undefined"!=typeof HTMLElement?HTMLElement:class{};class xs extends Rs{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(),te.debug("WidgeticWidget created",{instanceId:this.instanceId})}connectedCallback(){return t(this,void 0,void 0,(function*(){var e;if(!this.isWidgetConnected){this.isWidgetConnected=!0,te.debug("WidgeticWidget connected",{instanceId:this.instanceId});try{this.setLoadingState(!0);const t=rs(this),i=null!==(e=null==t?void 0:t.id)&&void 0!==e?e:this.getAttribute("composition-id");if(!i)throw new Error("composition-id attribute is required");ks(this);const n="widget"===(null==t?void 0:t.kind)?yield Qo(i):yield Jo(i);if("refused"===n.status)throw es(i,n.refusal),new Error("This embed is not authorized to be shown on this website.");const o="found"===n.status?n.payload:null;if(null==o?void 0:o.embedUrl){const e=Cs(this,o);return this.innerHTML="",this.appendChild(ts(o.embedUrl,this.getAttribute("width")||"400",this.getAttribute("height")||"300",i,e)),void this.setWidgetReady()}yield this.loadWidgetData(i),this.widgetData&&(yield this.loadWidgetModule()),yield this.initializeWidget(),this.setupResponsiveBehavior(),this.setupEventHandling(),this.setWidgetReady()}catch(e){te.error("WidgeticWidget initialization failed",{instanceId:this.instanceId,error:e}),this.setErrorState(e)}}}))}disconnectedCallback(){this.isWidgetConnected&&(te.debug("WidgeticWidget disconnected",{instanceId:this.instanceId}),this.cleanup(),this.isWidgetConnected=!1)}attributeChangedCallback(e,t,i){if(this.isInitialized&&t!==i){switch(te.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){te.warn("Invalid theme attribute",{instanceId:this.instanceId,theme:e})}}loadWidgetData(e){return t(this,void 0,void 0,(function*(){const t=ho();this.compositionData=yield t.getComposition(e),this.widgetData=yield t.getWidget(this.compositionData.widgetId),te.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=vo();this.loadedModule=yield e.loadModule(this.widgetData),te.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,te.debug("Widget initialized successfully",{instanceId:this.instanceId})}catch(e){throw te.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})),te.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})),te.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})),te.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){te.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(),te.debug("Widget cleanup complete",{instanceId:this.instanceId})}generateInstanceId(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}}const Ms="widgetic_autoscale_heights";function Ws(e){return""!==e&&"__proto__"!==e&&"constructor"!==e&&"prototype"!==e}function Os(){try{const e=localStorage.getItem(Ms);if(!e)return{};const t=JSON.parse(e);return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}catch(e){return{}}}function Ds(e,t=Date.now()){if(!Ws(e))return null;const i=Os(),n=Object.prototype.hasOwnProperty.call(i,e)?i[e]:void 0;if(!n||"number"!=typeof n.height||!Number.isFinite(n.height)||n.height<=0)return null;if("number"!=typeof n.lastUpdated||t-n.lastUpdated>864e5){try{delete i[e],localStorage.setItem(Ms,JSON.stringify(i))}catch(e){}return null}return n.height}function Ls(e,t,i,n=Date.now()){if(Ws(e)&&Number.isFinite(t)&&!(t<=0))try{const o=Os();o[e]={compositionId:e,height:t,originalHeight:i,lastUpdated:n},localStorage.setItem(Ms,JSON.stringify(o))}catch(e){}}class Us{constructor(){this.observers=new Map,this.mutationObservers=new Map,this.timeouts=new Map,this.animationIds=new Map,this.storageKey=Ms}static getInstance(){return Us.instance||(Us.instance=new Us),Us.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){return Ds(e)}storeHeight(e,t,i){Ls(e,t,i)}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,l=i=>{const o=i-a,r=Math.min(o/n,1),c=1-Math.pow(1-r,3),u=d+s*c;if(e.style.height=`${u}px`,r<1){const t=requestAnimationFrame(l);this.animationIds.set(e.id||e.tagName,t)}else e.style.height=`${t}px`,this.animationIds.delete(e.id||e.tagName)},c=requestAnimationFrame(l);this.animationIds.set(e.id||e.tagName,c)}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 Ps{static getInstance(){return Ps.instance||(Ps.instance=new Ps),Ps.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.isPageUnloading=!1,this.pausedByManagerAt=new Map,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){var t;const{type:i,compositionId:n,config:o,data:s}=e;if(o&&Object.keys(o).length>0){const e=this.widgetConfigs.get(n)||{autoPause:!0,mediaType:"both",priority:5,persistState:!0,allowSimultaneous:[],autoResume:!0,autoResumeTimeout:this.defaultAutoResumeTimeout,globalVolume:!0};this.widgetConfigs.set(n,Object.assign(Object.assign({},e),o))}switch(i){case"play":this.handlePlayEvent(n,o,s);break;case"pause":this.handlePauseEvent(n,s,o);break;case"stop":case"ended":this.handleStopEvent(n);break;case"seeking":case"seeked":this.handleSeekingEvent(n,null!==(t=null==s?void 0:s.position)&&void 0!==t?t:null==s?void 0:s.currentTime,o,s);break;case"timeupdate":case"progress":case"durationchange":case"loadedmetadata":this.handleTimeUpdateEvent(n,o,s);break;case"volumechange":this.handleVolumeEvent(n,null==s?void 0:s.volume,o);break;case"trackchange":this.handleTrackChangeEvent(n,s,o);break;case"playlistchange":this.handlePlaylistChangeEvent(n,s,o)}this.emitToListeners(n,e),!1!==(null==o?void 0:o.persistState)&&this.persistState(),this.dispatchGlobalEvent(e)}getOrCreateMediaState(e,t={},i="paused",n={}){var o;const s=this.playingWidgets.get(e);if(s)return s;const r={compositionId:e,mediaType:(null==n?void 0:n.mediaType)||t.mediaType||"both",state:i,priority:t.priority||5,startedAt:Date.now(),duration:"number"==typeof(null==n?void 0:n.duration)?n.duration:void 0,position:"number"==typeof(null==n?void 0:n.position)?n.position:"number"==typeof(null==n?void 0:n.currentTime)?n.currentTime:0,title:null==n?void 0:n.title,volume:"number"==typeof(null==n?void 0:n.volume)?n.volume:void 0,playlist:null==n?void 0:n.playlist,autoResume:null===(o=t.autoResume)||void 0===o||o,lastInteraction:Date.now()};return this.playingWidgets.set(e,r),r}handlePlayEvent(e,t={},i={}){var n,o,s,r;this.pausedByManagerAt.delete(e);const a=this.playingWidgets.get(e),d=i.mediaType||t.mediaType||(null==a?void 0:a.mediaType)||"both",l=t.priority||(null==a?void 0:a.priority)||5,c="number"==typeof i.position?i.position:"number"==typeof i.currentTime?i.currentTime:null!==(n=null==a?void 0:a.position)&&void 0!==n?n:0,u={compositionId:e,mediaType:d,state:"playing",priority:l,startedAt:Date.now(),duration:"number"==typeof i.duration?i.duration:null==a?void 0:a.duration,position:c,title:null!==(o=i.title)&&void 0!==o?o:null==a?void 0:a.title,volume:"number"==typeof i.volume?i.volume:null==a?void 0:a.volume,playlist:i.playlist?Object.assign(Object.assign({},null==a?void 0:a.playlist),i.playlist):null==a?void 0:a.playlist,autoResume:null===(r=null!==(s=t.autoResume)&&void 0!==s?s:null==a?void 0:a.autoResume)||void 0===r||r,lastInteraction:Date.now()};!1!==t.autoPause&&this.pauseConflictingWidgets(e,d,l,t.allowSimultaneous||[]),this.playingWidgets.set(e,u)}handlePauseEvent(e,t={},i={}){const n=this.getOrCreateMediaState(e,i,"paused",t);n.state="paused";const o="number"==typeof(null==t?void 0:t.position)?t.position:null==t?void 0:t.currentTime;"number"==typeof o&&(n.position=o),"number"==typeof(null==t?void 0:t.duration)&&(n.duration=t.duration),"number"==typeof(null==t?void 0:t.volume)&&(n.volume=t.volume),(null==t?void 0:t.title)&&(n.title=t.title),(null==t?void 0:t.playlist)&&(n.playlist=Object.assign(Object.assign({},n.playlist),t.playlist)),n.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,i={},n={}){const o=this.getOrCreateMediaState(e,i,"paused",n);"number"==typeof t&&(o.position=t),"number"==typeof(null==n?void 0:n.duration)&&(o.duration=n.duration),(null==n?void 0:n.playlist)&&(o.playlist=Object.assign(Object.assign({},o.playlist),n.playlist)),o.lastInteraction=Date.now()}handleTimeUpdateEvent(e,t={},i={}){var n;const o="playing"===(null===(n=this.playingWidgets.get(e))||void 0===n?void 0:n.state),s=!0===(null==i?void 0:i.playing)?"playing":"paused",r=this.getOrCreateMediaState(e,t,s,i),a="number"==typeof(null==i?void 0:i.position)?i.position:null==i?void 0:i.currentTime;"number"==typeof a&&(r.position=a),"number"==typeof(null==i?void 0:i.duration)&&Number.isFinite(i.duration)&&(r.duration=i.duration),"number"==typeof(null==i?void 0:i.volume)&&(r.volume=i.volume);const d=!0===(null==i?void 0:i.playing)||"boolean"!=typeof(null==i?void 0:i.playing)&&"playing"===(null==i?void 0:i.state),l=!1===(null==i?void 0:i.playing)||"paused"===(null==i?void 0:i.state)||"stopped"===(null==i?void 0:i.state);if(d){const i=this.pausedByManagerAt.get(e);i&&Date.now()-i<500?(r.state="paused",this.sendPauseCommand(e,void 0,!1)):(r.state="playing",o||!1===t.autoPause||this.pauseConflictingWidgets(e,r.mediaType,r.priority,t.allowSimultaneous||[]))}else l&&(r.state="stopped"===(null==i?void 0:i.state)?"stopped":"paused");(null==i?void 0:i.title)&&(r.title=i.title),(null==i?void 0:i.playlist)&&(r.playlist=Object.assign(Object.assign({},r.playlist),i.playlist)),r.lastInteraction=Date.now()}handleVolumeEvent(e,t,i={}){const n=this.getOrCreateMediaState(e,i,"paused",{volume:t}),o=this.widgetConfigs.get(e)||i;n&&"number"==typeof t&&(n.lastInteraction=Date.now(),(null==o?void 0:o.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),n.volume=this.globalVolumeState.muted?0:this.globalVolumeState.volume):n.volume=t)}handleTrackChangeEvent(e,t={},i={}){const n=this.getOrCreateMediaState(e,i,"paused",t),o=(null==t?void 0:t.playlist)||Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"number"==typeof(null==t?void 0:t.currentTrack)?{currentTrack:t.currentTrack}:{}),"number"==typeof(null==t?void 0:t.trackIndex)?{currentTrack:t.trackIndex}:{}),"number"==typeof(null==t?void 0:t.totalTracks)?{totalTracks:t.totalTracks}:{}),(null==t?void 0:t.trackId)?{trackId:t.trackId}:{}),(null==t?void 0:t.trackTitle)||(null==t?void 0:t.title)?{trackTitle:t.trackTitle||t.title}:{});if(Object.keys(o).length>0&&(n.playlist=Object.assign(Object.assign({currentTrack:0,totalTracks:1},n.playlist),o),n.title=o.trackTitle||(null==t?void 0:t.title)||n.title),n.position="number"==typeof(null==t?void 0:t.position)?t.position:0,"boolean"==typeof(null==t?void 0:t.playing)){const o="playing"===n.state;n.state=t.playing?"playing":"paused",t.playing&&(this.pausedByManagerAt.delete(e),o||!1===i.autoPause||this.pauseConflictingWidgets(e,n.mediaType,n.priority,i.allowSimultaneous||[]))}n.lastInteraction=Date.now()}handlePlaylistChangeEvent(e,t={},i={}){const n=this.getOrCreateMediaState(e,i,"paused",t);(null==t?void 0:t.playlist)&&(n.playlist=Object.assign(Object.assign({},n.playlist),t.playlist),n.lastInteraction=Date.now())}pauseConflictingWidgets(e,t,i,n){const o=[];for(const[i,s]of this.playingWidgets){if(i===e||"playing"!==s.state)continue;this.isSimultaneousAllowed(s.mediaType,t,n)||o.push(i)}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)))}resolveHostElements(e){if("undefined"==typeof document)return[];const t=[`[data-widgetic-id="${e}"]`,`[data-composition-id="${e}"]`,`[composition-id="${e}"]`,`[compositionid="${e}"]`,`[composition="${e}"]`,`widgetic[composition-id="${e}"]`,`[widget="${e}"]`,`[widget-id="${e}"]`,`[widgetid="${e}"]`,`[data-widget-id="${e}"]`,`widgetic[widget="${e}"]`,`widgetic[widget-id="${e}"]`].join(", ");return Array.from(document.querySelectorAll(t))}resolveIframeTargetOrigin(e){var t;const i=e.getAttribute("src")||e.src;if(i)try{const e=new URL(i,"undefined"!=typeof window&&(null===(t=window.location)||void 0===t?void 0:t.href)?window.location.href:"https://widgetic.com").origin;if(e&&"null"!==e)return e}catch(e){}return"*"}dispatchCommandToHostAndIframe(e,t){var i;const n=this.resolveHostElements(e);if(0===n.length)return!1;for(const e of n){const n="iframe"===e.tagName.toLowerCase()?e:e.querySelector("iframe");if(null==n?void 0:n.contentWindow){const e=this.resolveIframeTargetOrigin(n);try{n.contentWindow.postMessage(t,e)}catch(e){try{n.contentWindow.postMessage(t,"*")}catch(e){}}}e.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:t}));const o=e.querySelector("[data-widgetic-direct]"),s=null===(i=null==o?void 0:o.shadowRoot)||void 0===i?void 0:i.querySelector(".widgetic-direct-target");s&&s.dispatchEvent(new CustomEvent("widgetic:media:command",{detail:t,bubbles:!0,composed:!0}))}return!0}sendPauseCommand(e,t,i=!0){if(i){this.pausedByManagerAt.set(e,Date.now());const t=this.playingWidgets.get(e);t&&(t.state="paused")}this.dispatchCommandToHostAndIframe(e,Object.assign({type:"widgetic:media:command",command:"pause",compositionId:e},"number"==typeof t?{position:t}:{}))}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){const t=this.playingWidgets.get(e);this.dispatchCommandToHostAndIframe(e,Object.assign({type:"widgetic:media:command",command:"play",compositionId:e},"number"==typeof(null==t?void 0:t.position)?{position:t.position}:{}))}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(){var e;if("undefined"!=typeof localStorage)try{const t=localStorage.getItem(this.storageKey);if(t){const i=JSON.parse(t);if(i.version!==this.storageVersion)return void this.clearPersistedState();const n=864e5;if(i.timestamp&&Date.now()-i.timestamp>n)return void this.clearPersistedState();const o=[];for(const[e,t]of Object.entries(i.playingWidgets||{})){const e=t;e.compositionId&&e.mediaType&&e.state&&o.push(e)}const s=null===(e=o.filter((e=>"playing"===e.state)).sort(((e,t)=>{const i=e.lastInteraction||e.startedAt||0,n=t.lastInteraction||t.startedAt||0;return n!==i?n-i:(t.priority||5)-(e.priority||5)}))[0])||void 0===e?void 0:e.compositionId;for(const e of o)"playing"===e.state&&e.compositionId!==s&&(e.state="paused"),this.playingWidgets.set(e.compositionId,e)}}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",(()=>{if(document.hidden&&!this.isPageUnloading){const e=this.getPlayingWidgets();for(const t of e)this.sendPauseCommand(t.compositionId,t.position,!1)}}))}setupUnloadHandler(){if("undefined"==typeof window)return;const e=()=>{this.isPageUnloading=!0,this.persistState()};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e)}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={}){var t,i;if(!this.autoResumeEnabled)return;const{autoResumePlayback:n=!0,maxStateAge:o=this.defaultAutoResumeTimeout,respectTimeouts:s=!0}=e,r=Date.now(),a=[];for(const[e,d]of this.playingWidgets){const l=this.widgetConfigs.get(e)||{persistState:!0,autoResume:null===(t=d.autoResume)||void 0===t||t};(null!==(i=l.autoResume)&&void 0!==i?i:d.autoResume)&&!1!==l.persistState&&d.lastInteraction&&(!s||r-d.lastInteraction<=(l.autoResumeTimeout||o))&&("playing"===d.state||n&&"paused"===d.state)&&a.push(d)}if(a.length>0){a.sort(((e,t)=>e.priority!==t.priority?t.priority-e.priority:(t.lastInteraction||0)-(e.lastInteraction||0)));let e=!1;for(const t of a)n&&"playing"===t.state&&!e?(e=!0,this.resumeWidget(t.compositionId)):this.sendRestoreStateCommand(t.compositionId,Object.assign(Object.assign({},t),{state:"paused"}))}}resumeWidget(e){const t=this.playingWidgets.get(e);if(!t)return!1;if("playing"===t.state){this.pausedByManagerAt.delete(e);const i=this.widgetConfigs.get(e);!1!==(null==i?void 0:i.autoPause)&&this.pauseConflictingWidgets(e,t.mediaType,t.priority,(null==i?void 0:i.allowSimultaneous)||[])}return this.sendRestoreStateCommand(e,t),"playing"===t.state?setTimeout((()=>{var i;"playing"===(null===(i=this.playingWidgets.get(e))||void 0===i?void 0:i.state)&&this.sendPlayCommand(e,t.position)}),100):"paused"===t.state&&setTimeout((()=>{var i;"playing"!==(null===(i=this.playingWidgets.get(e))||void 0===i?void 0:i.state)&&this.sendPauseCommand(e,t.position,!1)}),100),!0}sendRestoreStateCommand(e,t){const i={type:"widgetic:media:command",command:"restore",compositionId:e,state:{state:t.state,playing:"playing"===t.state,position:"number"==typeof t.position?t.position:0,volume:"number"==typeof t.volume?t.volume:1,title:t.title,playlist:t.playlist,duration:t.duration}};this.dispatchCommandToHostAndIframe(e,i)}sendPlayCommand(e,t){const i={type:"widgetic:media:command",command:"play",compositionId:e,position:t};this.dispatchCommandToHostAndIframe(e,i)}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);!1!==(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){const i={type:"widgetic:media:command",command:"setVolume",compositionId:e,volume:Math.max(0,Math.min(1,t))};this.dispatchCommandToHostAndIframe(e,i)}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 _s=null;function zs(){return _s||(_s=Ps.getInstance()),_s}var qs=Object.freeze({__proto__:null,MediaManager:Ps,getMediaManager:zs,resetMediaManager:function(){_s&&(_s.destroy(),_s=null)}});class js{static getInstance(){return js.instance||(js.instance=new js),js.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,s=Object.assign(Object.assign({contentType:"custom",persistState:!0,autoResume:!0,debounceDelay:500,trackMetadata:!0},this.widgetConfigs.get(i)),n);switch(void 0!==s.autoResumePosition&&void 0===n.autoResume&&(s.autoResume=s.autoResumePosition),this.widgetConfigs.set(i,s),t){case"position":case"navigate":this.handlePositionChangeEvent(i,s,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),!1!==s.persistState&&this.persistState(),this.dispatchGlobalEvent(e)}handlePositionChangeEvent(e,t,i={}){var n,o,s,r,a,d,l,c,u,h;const g=this.contentStates.get(e),p="number"==typeof(null==i?void 0:i.currentIndex)?i.currentIndex:"number"==typeof(null==i?void 0:i.index)?i.index:null!==(n=null==g?void 0:g.currentIndex)&&void 0!==n?n:0,m="number"==typeof(null==i?void 0:i.totalItems)?i.totalItems:"number"==typeof(null==i?void 0:i.total)?i.total:null!==(o=null==g?void 0:g.totalItems)&&void 0!==o?o:0,f=void 0!==(null==i?void 0:i.metadata)||void 0!==(null==g?void 0:g.metadata)?Object.assign(Object.assign({},null==g?void 0:g.metadata),null==i?void 0:i.metadata):void 0,v={compositionId:e,contentType:t.contentType||(null==g?void 0:g.contentType)||"custom",currentIndex:p,totalItems:m,currentItemId:null!==(r=null!==(s=null==i?void 0:i.currentItemId)&&void 0!==s?s:null==i?void 0:i.itemId)&&void 0!==r?r:null==g?void 0:g.currentItemId,currentItemTitle:null!==(l=null!==(d=null!==(a=null==i?void 0:i.currentItemTitle)&&void 0!==a?a:null==i?void 0:i.itemTitle)&&void 0!==d?d:null==i?void 0:i.title)&&void 0!==l?l:null==g?void 0:g.currentItemTitle,lastUpdated:Date.now(),autoResume:null===(h=null!==(u=null!==(c=t.autoResume)&&void 0!==c?c:t.autoResumePosition)&&void 0!==u?u:null==g?void 0:g.autoResume)||void 0===h||h,lastInteraction:Date.now(),metadata:f};this.contentStates.set(e,v)}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={}){var t,i,n,o;if(!this.autoResumeEnabled)return;const{autoResumePosition:s=!0,maxStateAge:r=this.defaultAutoResumeTimeout,respectTimeouts:a=!0}=e,d=Date.now(),l=[];for(const[e,c]of this.contentStates){const u=this.widgetConfigs.get(e),h=null!==(n=null!==(i=null!==(t=null==u?void 0:u.autoResume)&&void 0!==t?t:null==u?void 0:u.autoResumePosition)&&void 0!==i?i:c.autoResume)&&void 0!==n&&n,g=null===(o=null==u?void 0:u.persistState)||void 0===o||o;h&&g&&c.lastInteraction&&(!a||d-c.lastInteraction<=((null==u?void 0:u.autoResumeTimeout)||r))&&s&&l.push(c)}l.length>0&&l.forEach((e=>{this.resumeWidgetPosition(e.compositionId)}))}resumeWidgetPosition(e){const t=this.contentStates.get(e);return!!t&&(this.sendRestorePositionCommand(e,t),!0)}resolveHostElement(e){return"undefined"==typeof document?null:document.querySelector(`[data-widgetic-id="${e}"], [data-composition-id="${e}"], [composition-id="${e}"], widgetic[composition-id="${e}"], [widget="${e}"], [widget-id="${e}"], widgetic[widget="${e}"], widgetic[widget-id="${e}"]`)}resolveIframeTargetOrigin(e){var t;const i=e.getAttribute("src")||e.src;if(i)try{const e=new URL(i,"undefined"!=typeof window&&(null===(t=window.location)||void 0===t?void 0:t.href)?window.location.href:"https://widgetic.com").origin;if(e&&"null"!==e)return e}catch(e){}return"*"}sendRestorePositionCommand(e,t){var i;const n=this.resolveHostElement(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}},s="iframe"===n.tagName.toLowerCase()?n:n.querySelector("iframe");if(null==s?void 0:s.contentWindow){const e=this.resolveIframeTargetOrigin(s);try{s.contentWindow.postMessage(o,e)}catch(e){try{s.contentWindow.postMessage(o,"*")}catch(e){}}}n.dispatchEvent(new CustomEvent("widgetic:content:command",{detail:o}));const r=n.querySelector("[data-widgetic-direct]"),a=null===(i=null==r?void 0:r.shadowRoot)||void 0===i?void 0:i.querySelector(".widgetic-direct-target");a&&a.dispatchEvent(new CustomEvent("widgetic:content:command",{detail:o,bubbles:!0,composed:!0}))}}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);!1!==(null==o?void 0:o.persistState)&&this.persistState()}}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 Bs=null;function $s(){return Bs||(Bs=js.getInstance()),Bs}class Ns{constructor(){this.autoScaleManager=Us.getInstance(),"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-widget")||(customElements.define("widgetic-widget",xs),te.info("WidgeticWidget custom element registered")))}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,l=document.createElement("widgetic-widget");if(l.setAttribute("composition-id",t),l.setAttribute("width",String(i)),l.setAttribute("height",String(n)),l.setAttribute("resize",o),"boolean"==typeof s?l.setAttribute("autoscale",s?"true":"false"):s&&"object"==typeof s?(l.setAttribute("autoscale","true"),void 0!==s.minHeight&&l.setAttribute("autoscale-min-height",String(s.minHeight)),void 0!==s.maxHeight&&l.setAttribute("autoscale-max-height",String(s.maxHeight)),void 0!==s.debounceDelay&&l.setAttribute("autoscale-debounce",String(s.debounceDelay)),void 0!==s.threshold&&l.setAttribute("autoscale-threshold",String(s.threshold)),void 0!==s.animate&&l.setAttribute("autoscale-animate",String(s.animate)),void 0!==s.animationDuration&&l.setAttribute("autoscale-animation-duration",String(s.animationDuration))):l.setAttribute("autoscale","false"),l.setAttribute("adaptive",String(r)),a&&Object.keys(a).length>0){zs().registerWidget(t,a),this.setupCustomElementMediaListener(l,t)}if(d&&Object.keys(d).length>0){$s().registerWidget(t,d),this.setupCustomElementContentListener(l,t)}return{id:`custom-${t}-${Date.now()}`,element:l,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:()=>{l._mediaCommandCleanup&&l._mediaCommandCleanup(),l._mediaObserverCleanup&&l._mediaObserverCleanup(),l._contentPositionCleanup&&l._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=zs(),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=$s(),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)}}}var Fs=Object.freeze({__proto__:null,CustomElementRenderer:Ns});const Ks={close:"Close",closeOverlay:"Close overlay",interactiveWidget:"Interactive widget"},Hs=new Map([["fr",{close:"Fermer",closeOverlay:"Fermer la fenêtre",interactiveWidget:"Widget interactif"}],["de",{close:"Schließen",closeOverlay:"Fenster schließen",interactiveWidget:"Interaktives Widget"}],["es",{close:"Cerrar",closeOverlay:"Cerrar ventana",interactiveWidget:"Widget interactivo"}],["pt",{close:"Fechar",closeOverlay:"Fechar janela",interactiveWidget:"Widget interativo"}],["nl",{close:"Sluiten",closeOverlay:"Venster sluiten",interactiveWidget:"Interactieve widget"}],["da",{close:"Luk",closeOverlay:"Luk vinduet",interactiveWidget:"Interaktiv widget"}],["sv",{close:"Stäng",closeOverlay:"Stäng fönstret",interactiveWidget:"Interaktiv widget"}],["zh",{close:"关闭",closeOverlay:"关闭窗口",interactiveWidget:"交互式小组件"}],["ar",{close:"إغلاق",closeOverlay:"إغلاق النافذة",interactiveWidget:"ويجت تفاعلي"}],["he",{close:"סגירה",closeOverlay:"סגירת החלון",interactiveWidget:"וידג'ט אינטראקטיבי"}],["fa",{close:"بستن",closeOverlay:"بستن پنجره",interactiveWidget:"ویجت تعاملی"}],["ur",{close:"بند کریں",closeOverlay:"ونڈو بند کریں",interactiveWidget:"انٹرایکٹو ویجٹ"}]]);function Vs(e,t=function(){var e,t;return"undefined"==typeof document?"":(null===(e=document.body)||void 0===e?void 0:e.getAttribute("lang"))||(null===(t=document.documentElement)||void 0===t?void 0:t.getAttribute("lang"))||""}()){const i=function(e){var t,i;const n=(null!=e?e:"").trim().replace(/_/g,"-").toLowerCase().split("-"),o="iw"===n[0]?"he":null!==(t=n[0])&&void 0!==t?t:"",s=null!==(i=n[1])&&void 0!==i?i:"";return("zh"!==o||"tw"!==s&&"hk"!==s&&"hant"!==s)&&Hs.has(o)?o:null}(t),n=null===i?void 0:Hs.get(i);return(null!=n?n:Ks)[e]}Hs.keys();class Gs{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(),te.info("WidgeticMessenger initialized",{securityOptions:this.securityOptions})}setupAllowedOrigins(e){en.CLIENT_URL&&this.allowedOrigins.add(en.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,te.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 te.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)?(te.warn("Message signature validation failed",{instanceId:t.instanceId}),null):t:(te.warn("Invalid message structure",{message:t}),null)}catch(t){return te.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(te.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){te.error("Message handler error",{error:e,instanceId:t.instanceId})}else te.debug("No handler for message",{instanceId:t.instanceId,type:t.type})}handleHeartbeat(e){te.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){te.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 Dr})).then((({getSecurityManager:o})=>{const s=o().validateTextFieldUpdate(e.instanceId,t,i,n);if(!s.allowed)return te.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}));te.debug("Text field change received",{instanceId:e.instanceId,fieldId:t,textLength:i.length,sanitized:!(!s.sanitizedText||s.sanitizedText===i)}),Promise.resolve().then((function(){return qd})).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=>{te.warn("Failed to handle text field change",{error:t,instanceId:e.instanceId})}))})).catch((t=>{te.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}))):te.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&&(te.debug("Dispatching custom event",{instanceId:e.instanceId,eventName:t,subscriberCount:s.size}),s.forEach((o=>{try{o(i,n)}catch(i){te.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){te.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"))):te.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),te.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),te.debug("Message handler unregistered",{instanceId:e})}sendMessage(e,t){const i=document.querySelector(`[data-widgetic-id="${e}"]`);if(!i||!i.contentWindow)return te.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),"*"),te.debug("Message sent",{instanceId:e,type:o.type,sequence:n})}catch(i){te.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)):te.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),te.debug("Heartbeat started",{instanceId:e,interval:this.securityOptions.heartbeatInterval})}stopHeartbeat(e){const t=this.heartbeatIntervals.get(e);t&&(clearInterval(t),this.heartbeatIntervals.delete(e),te.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(),te.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 qd}));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 qd}));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 qd}));return t().getTextField(e,i)})),clearTextField:i=>t(this,void 0,void 0,(function*(){const{getTextFieldManager:t}=yield Promise.resolve().then((function(){return qd}));t().clearTextField(e,i)})),getTextFields:()=>t(this,void 0,void 0,(function*(){const{getTextFieldManager:t}=yield Promise.resolve().then((function(){return qd}));return t().getWidgetTextFields(e)})),clearAllTextFields:()=>t(this,void 0,void 0,(function*(){const{getTextFieldManager:t}=yield Promise.resolve().then((function(){return qd}));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),te.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),te.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"}),te.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"}),te.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)})),te.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),te.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),te.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 Xs=null;function Ys(e){return Xs||(Xs=new Gs(e)),Xs}var Js=Object.freeze({__proto__:null,WidgeticMessenger:Gs,getMessenger:Ys,resetMessenger:function(){Xs&&(Xs.cleanup(),Xs=null)}});class Qs{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),te.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),te.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 l,c;switch(o){case"fill-width":l=a,c=l/e.aspectRatio,s&&c>d&&(c=d,l=c*e.aspectRatio);break;case"fill-height":c=d,l=c*e.aspectRatio,s&&l>a&&(l=a,c=l/e.aspectRatio);break;case"fixed":default:l=e.originalWidth,c=e.originalHeight;break;case"fixed-height":l=a,c=e.originalHeight;break;case"fixed-width":l=e.originalWidth,c=d;break;case"allow-scale-down":const t=a/e.originalWidth,i=d/e.originalHeight,n=Math.min(1,Math.min(t,i));l=e.originalWidth*n,c=e.originalHeight*n;break;case"fill":l=a,c=d}this.setElementSize(t,l,c,n),this.options.enableAdaptive&&n.adaptive&&this.handleAdaptiveBreakpoint(e,a),te.debug("Resize mode applied",{widgetId:e.widgetId,resizeMode:o,containerSize:{width:a,height:d},newSize:{width:l,height:c}})}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 Zs=null;class er{constructor(){this.observers=new Map,this.callbacks=new Map,this.currentStates=new Map,this.debounceTimers=new Map,"undefined"==typeof ResizeObserver&&te.warn("ResizeObserver not available, responsive breakpoints will not work")}registerWidget(e,t,i,n){if("undefined"==typeof ResizeObserver)return void te.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),te.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),te.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 te.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),te.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),te.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),te.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);te.debug("ResponsiveManager cleanup complete")}}let tr=null;function ir(){return tr||(tr=new er),tr}class nr{constructor(){this.messageQueue=new Map,this.iframeRegistry=new Map,this.loadingTimeouts=new Map,this.autoScaleManager=Us.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:l=!0,sandbox:c=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,c,u),p.width=i.toString(),p.height=n.toString(),p.frameBorder="0",p.scrolling="no",l&&(p.allowFullscreen=!0,p.setAttribute("allowfullscreen","")),p.title=`Widgetic Widget ${t}`,p.setAttribute("aria-label",`${Vs("interactiveWidget")}: ${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=Qs.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 k="lazy"===h,T=new Promise(((e,i)=>{let n=null;k||(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 Qs({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"),k||(yield T);const S=`iframe-${t}-${Date.now()}`;if(te.info("Enhanced iframe widget rendered successfully",{compositionId:t,size:{width:i,height:n},resize:o,autoscale:s,responsive:a,sandbox:c.join(" "),features:u.join("; ")}),m.media&&Object.keys(m.media).length>0){zs().registerWidget(t,m.media),this.setupIframeMediaListener(p,t)}if(e.content&&Object.keys(e.content).length>0){$s().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 te.error("Enhanced iframe widget rendering failed",{compositionId:t,error:e}),this.removeLoadingIndicator(d),e}}))}renderWidgets(e){return t(this,void 0,void 0,(function*(){te.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{te.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 te.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||[en.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=`${en.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 nn();o.set("apiKey",e)}catch(e){te.warn("Failed to get auth token for iframe",e),en.API_KEY&&o.set("apiKey",en.API_KEY)}const s=`${n}?${o.toString()}`;return te.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)},te.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++,te.warn(`Iframe loading failed, retrying (${s}/${o})`,{compositionId:t}),setTimeout((()=>{e.src=e.src+"&retry="+s}),1e3*s)):(te.error("Iframe loading failed after retries",{compositionId:t,retryCount:o}),this.handleIframeFallback(e,t))},a=setTimeout((()=>{te.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)),te.debug("Iframe loaded successfully",{compositionId:t})})),e.addEventListener("error",(()=>{te.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=Ys({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:sn(),timestamp:Date.now(),sdkVersion:"2.0",mode:"iframe"},timestamp:Date.now(),version:"1.0"}),te.debug("Initial config sent to iframe",{compositionId:t})})),e.__messenger=n,e.__messagingCompositionId=t,te.debug("Enhanced iframe messaging setup complete",{compositionId:t})}handleEnhancedIframeMessage(e,t){switch(te.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:te.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})),te.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})),te.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})),te.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})),te.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})),te.debug("Iframe interaction event",{instanceId:t.instanceId,eventType:t.payload.type})}sendMessageToIframe(e,t,i){Ys().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),te.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=ir(),s=Ys(),r={breakpoint:n,debounceDelay:150},a=`responsive-${i}`;o.registerWidget(a,t,r,(t=>{te.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,te.info("Responsive monitoring enabled for iframe",{compositionId:i,breakpoint:n,containerId:a})}setupIframeMediaListener(e,t){const i=zs(),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","seeked","timeupdate","progress","volumechange","trackchange","playlistchange"].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.detail||n.data.payload||n.data.data||{}})}}};window.addEventListener("message",n),e._mediaListenerCleanup=()=>{window.removeEventListener("message",n)}}setupIframeContentListener(e,t){const i=$s(),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)}}}let or=null;var sr=Object.freeze({__proto__:null,IframeRenderer:nr,getIframeRenderer:function(){return or||(or=new nr),or}});class rr{constructor(){this.batchClient=ho(),this.moduleLoader=vo(),this.customElementRenderer=new Ns,this.iframeRenderer=new nr,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 l=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(l)).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 ar=null;function dr(){return ar||(ar=new rr),ar}var lr=Object.freeze({__proto__:null,WidgetRenderer:rr,getWidgetRenderer:dr,resetWidgetRenderer:function(){ar&&ar.cleanupAll(),ar=null}});function cr(){var e;try{if("undefined"!=typeof document){const e=document.querySelectorAll("script[src*='embed-sdk']");for(const t of Array.from(e))if("off"===t.getAttribute("data-widgetic-telemetry"))return!1}if("undefined"!=typeof window&&!1===(null===(e=window.WidgeticConfig)||void 0===e?void 0:e.telemetry))return!1}catch(e){}return!0}class ur{constructor(e={}){this.metrics=[],this.webVitals={},this.widgetMetrics=new Map,this.isTracking=!1,this.config=Object.assign({enableTracking:gn.ENABLE_PERFORMANCE_TRACKING,enableWebVitals:!0,enableWidgetMetrics:!0,enableResourceTracking:!0,enableBudgetMonitoring:!0,sampleRate:gn.PERFORMANCE_SAMPLE_RATE,maxMetricsBuffer:gn.MAX_METRICS_BUFFER,axiomApiEndpoint:gn.AXIOM_API_ENDPOINT,statsigApiEndpoint:gn.STATSIG_API_ENDPOINT,budgets:[{metric:"lcp",threshold:gn.LCP_THRESHOLD,warningThreshold:gn.LCP_WARNING_THRESHOLD,enabled:!0},{metric:"fid",threshold:gn.FID_THRESHOLD,warningThreshold:gn.FID_WARNING_THRESHOLD,enabled:!0},{metric:"cls",threshold:gn.CLS_THRESHOLD,warningThreshold:gn.CLS_WARNING_THRESHOLD,enabled:!0},{metric:"widget-load",threshold:gn.WIDGET_LOAD_THRESHOLD,warningThreshold:gn.WIDGET_LOAD_WARNING_THRESHOLD,enabled:!0},{metric:"bundle-size",threshold:gn.BUNDLE_SIZE_THRESHOLD,warningThreshold:gn.BUNDLE_SIZE_WARNING_THRESHOLD,enabled:!0}]},e),this.navigationStart=performance.now(),this.init()}init(){"undefined"!=typeof window&&this.config.enableTracking&&cr()&&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;if(!cr())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 hr=null;function gr(e){return hr||(hr=new ur(e)),hr}function pr(e={}){return hr=new ur(e),hr}var mr=Object.freeze({__proto__:null,PerformanceMonitor:ur,getPerformanceMonitor:gr,initializePerformanceMonitoring:pr});class fr{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),te.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),te.debug("Portal host created",{target:this.options.target,host:e})),e}mount(e){this.destroyed?te.warn("Cannot mount content to destroyed portal"):this.container?(this.content&&this.unmount(),e.style.pointerEvents="auto",this.content=e,this.container.appendChild(e),te.debug("Content mounted to portal",{content:e})):te.error("Portal container not available")}unmount(){this.content&&this.container&&this.container.contains(this.content)&&(this.container.removeChild(this.content),this.content=null,te.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,te.debug("Portal destroyed")}}getContainer(){return this.container}isDestroyed(){return this.destroyed}updateOptions(e){this.destroyed?te.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"))),te.debug("Portal options updated",{options:this.options}))}}function vr(e){return new fr(e)}const yr=e=>null!==e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"===Object.prototype.toString.call(e);function wr(e){if(Array.isArray(e))return e.map(wr);if(!yr(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(wr):yr(n)?wr(n):n}return t}function br(e){if(Array.isArray(e))return e.map(br);if(!yr(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(br):yr(n)?br(n):n}return t}class Ir{constructor(){this.sessionCache=null,this.sessionCacheExpiry=0,this.ownershipCache=new Map;const e=on(),t=new re({basePath:e.basePath,apiKey:e.apiKey,credentials:"include"});this.authApi=new Bi(t),this.compositionsApi=new Ni(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=wr(yield this.authApi.getSession());return e&&e.accessToken&&e.user?(this.sessionCache=e,this.sessionCacheExpiry=Date.now()+3e5,te.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 te.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=wr(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),te.debug("Composition ownership checked",{compositionId:e,isOwner:s,userId:n.session.user.id,compositionCreatorId:o.creatorId}),r}catch(t){te.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(),te.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 en.ENABLE_EDITING}}let kr=null;function Tr(){return kr||(kr=new Ir),kr}class Sr{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"===en.NODE_ENV?en.CLIENT_URL:`${en.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,te.info("UI SDK loaded successfully",{basePath:this.config.basePath,version:this.config.version}),this.sdkInstance}catch(e){throw te.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?(te.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),te.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)),te.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){te.warn("Error during UI SDK cleanup",{error:e})}this.sdkInstance=null}this.loadPromise=null,this.isLoading=!1,window.WidgeticUI&&delete window.WidgeticUI,te.debug("UI SDK cleanup complete")}))}preload(){return t(this,void 0,void 0,(function*(){try{yield this.loadUISdk(),te.debug("UI SDK preloaded successfully")}catch(e){te.warn("UI SDK preload failed",{error:e})}}))}}let Cr=null;function Ar(e){return Cr||(Cr=new Sr(e)),Cr}class Er{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=Tr(),n=yield t.checkCompositionOwnership(i);n.canEdit?(yield this.createOverlay(e,i,!0),te.debug("Editor overlay added for owned composition",{compositionId:i})):te.debug("Editor overlay not added - user cannot edit",{compositionId:i,reason:n.error})}catch(e){te.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),te.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 fr({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 te.warn("No editor session found",{compositionId:e});if(t.isOpen)return void te.debug("Editor already open",{compositionId:e});te.info("Opening composition editor",{compositionId:e});const i=Ar(),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=Ys().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")}te.info("Composition editor opened successfully",{compositionId:e})}catch(t){te.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{te.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),te.info("Composition saved successfully",{compositionId:e})}catch(t){te.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){te.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=Ar().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,te.info("Editor closed",{compositionId:e})}catch(t){te.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),te.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);te.debug("Editor overlay cleanup complete")}}let Rr=null;function xr(e){return Rr||(Rr=new Er(e)),Rr}var Mr=Object.freeze({__proto__:null,EditorOverlay:Er,getEditorOverlay:xr,resetEditorOverlay:function(){Rr&&(Rr.cleanup(),Rr=null)}});class Wr{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(),te.info("[SecurityManager] Initialized with config:",this.config)}static getInstance(e){return Wr.instance||(Wr.instance=new Wr(e)),Wr.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 te.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 te.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){te.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),te.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);te.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);te.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),te.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(),te.info("[SecurityManager] Destroyed")}}function Or(e){return Wr.getInstance(e)}var Dr=Object.freeze({__proto__:null,SecurityManager:Wr,getSecurityManager:Or});class Lr{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,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=Wr.getInstance(this.config),this.initializeCSP(),this.initializeDataSecurity(),this.initializeContentFilters(),this.initializeThreatDetection(),this.initializePrivacyControls(),te.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 Lr.instance||(Lr.instance=new Lr(e)),Lr.instance}initializeCSP(){this.config.csp&&(this.cspNonce=this.generateNonce(),this.setupCSPDirectives(),this.applyCSP(),te.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[data-widgetic-csp]");i||(i=document.createElement("meta"),i.httpEquiv="Content-Security-Policy",i.setAttribute("data-widgetic-csp","1"),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,te.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"]),te.info("[AdvancedSecurityManager] Data encryption initialized")}catch(e){te.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)})),te.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)})),te.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(),te.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){te.warn("[AdvancedSecurityManager] Failed to parse existing consent:",e)}}}initializeDataSubjectRights(){te.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 te.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){te.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 te.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 l=Math.min(10,d);o+=l,l>=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:l,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 te.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);te[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}),te.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"}}}var Ur=Object.freeze({__proto__:null,AdvancedSecurityManager:Lr,getAdvancedSecurityManager:function(e){return Lr.getInstance(e)}});class Pr{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=vr({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){te.warn("Native fullscreen failed, using CSS fullscreen",{error:e})}te.info("Widget entered fullscreen mode",{widgetId:e})}catch(t){throw te.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),te.info("Widget exited fullscreen mode",{widgetId:e})}catch(t){throw te.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=vr({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),te.info("Widget shown in overlay mode",{widgetId:e})}catch(t){throw te.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),te.info("Widget overlay hidden",{widgetId:e})}catch(t){throw te.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),te.info("Widget opened in popup",{widgetId:e}),r}catch(t){throw te.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,te.info("Widget popup closed",{widgetId:e})}catch(t){te.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.setAttribute("aria-label",Vs("close")),t.style.cssText="\n position: absolute;\n top: 20px;\n right: 20px;\n background: rgba(0, 0, 0, 0.7);\n color: white;\n border: none;\n border-radius: 50%;\n width: 40px;\n height: 40px;\n font-size: 20px;\n cursor: pointer;\n z-index: 100002;\n ",t.addEventListener("click",e),t}createOverlayContainer(e,t){const i=document.createElement("div");i.className="widgetic-overlay-container",i.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n background: ${t.backdrop?"rgba(0, 0, 0, 0.8)":"transparent"};\n `;const n=document.createElement("div");if(n.className="overlay-content",n.style.cssText=`\n max-width: ${t.maxWidth||"90vw"};\n max-height: ${t.maxHeight||"90vh"};\n background: white;\n border-radius: 8px;\n overflow: hidden;\n position: relative;\n `,t.showCloseButton){const t=this.createExitButton((()=>this.hideOverlay(e)));n.appendChild(t)}return i.appendChild(n),i}styleOverlayWidget(e,t){const i="mixed"===t.embedTarget&&!t.keepDimensions;let n=t.width||"100%",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 _r=null;function zr(e){return _r||(_r=new Pr(e)),_r}var qr=Object.freeze({__proto__:null,DisplayManager:Pr,getDisplayManager:zr,resetDisplayManager:function(){_r&&(_r.cleanupAll(),_r=null)}});class jr{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 Br{constructor(){this.deviceInfo=null}static getInstance(){return Br.instance||(Br.instance=new Br),Br.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 te.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?(te.debug("Widget restricted on mobile device"),!1):!(i.isDesktop&&!t)||(te.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 $r(){return Br.getInstance()}function Nr(e=!0,t=!0){return $r().checkDeviceRestrictions(e,t)}class Fr{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&&(te.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),te.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}),te.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++,te.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),te.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,te.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),te.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),te.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),te.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,te.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,te.debug("ScrollTrigger destroyed",{widgetId:this.widgetId}))}}class Kr{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&&(te.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)),te.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)),te.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),te.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()),te.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,te.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,te.debug("ExitIntentTrigger destroyed",{widgetId:this.widgetId}))}}const Hr={"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 Vr{constructor(){this.storageKey="widgetic-overlay-views",this.storageVersion="1.0"}static getInstance(){return Vr.instance||(Vr.instance=new Vr),Vr.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 te.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),te.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 te.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){te.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),te.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&&te.debug(`[RecurrenceManager] Cleaned up ${e.length} old view records`)}}class Gr{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=Vr.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(te.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),te.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 Fr({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 Kr({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;te.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;te.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 te.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=vr({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),te.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,te.debug("Widget returned to original position",{widgetId:this.widgetId}),this.dispatchEvent("overlay-hidden",{mode:this.mode}))}hideWidget(){this.element.style.display="none"}createOverlayContainer(){var e,t,i,n,o;const s=document.createElement("div");s.className="widgetic-trigger-overlay";const r=(null===(e=this.config.overlay)||void 0===e?void 0:e.position)||"bottom-right",a=(null===(t=this.config.overlay)||void 0===t?void 0:t.offset)||{x:20,y:20},d=this.hasOverlayBackground(),l=!!(null===(i=this.config.overlay)||void 0===i?void 0:i.fullWidth),c=this.getOverlayStyles(r,a,this.getOverlayZIndex(),l);if(s.style.cssText=c,d&&this.applyBackgroundStyling(s),null===(n=this.config.overlay)||void 0===n?void 0:n.closeButton){const e=this.createCloseButton(d,l);s.appendChild(e)}return(null===(o=this.config.overlay)||void 0===o?void 0:o.animation)&&s.classList.add(`widgetic-trigger-overlay-${this.config.overlay.animation}`),this.applyOverlayWidgetStyling(s),s}applyBackgroundStyling(e){var t,i;const n=null===(t=this.config.overlay)||void 0===t?void 0:t.background,o=(null==n?void 0:n.color)||"#000000",s=null!==(i=null==n?void 0:n.opacity)&&void 0!==i?i:.5,r=document.createElement("div");r.className="widgetic-trigger-overlay-backdrop",r.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background-color: ${o};\n opacity: ${s};\n pointer-events: auto;\n z-index: -1;\n `,r.addEventListener("click",(e=>{e.target===r&&this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),e.insertBefore(r,e.firstChild),e.classList.add("widgetic-trigger-overlay-has-background")}hasOverlayBackground(){var e,t,i;return!(!(null===(t=null===(e=this.config.overlay)||void 0===e?void 0:e.background)||void 0===t?void 0:t.enabled)&&!(null===(i=this.config.overlay)||void 0===i?void 0:i.backdrop))}getOverlayZIndex(){var e;const t=null===(e=this.config.overlay)||void 0===e?void 0:e.zIndex;return"number"!=typeof t||!Number.isFinite(t)||t<=0?99999999:Math.min(Math.floor(t),Sn)}getOverlayStyles(e,t,i,n){const[o,s]=Hr[e]||Hr["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",Vs("closeOverlay")),i.setAttribute("type","button");const n=this.createCloseSVG();i.appendChild(n);const o=t?"\n position: absolute;\n top: 8px;\n right: 8px;\n ":e?"\n position: absolute;\n top: 20px;\n right: 20px;\n ":"\n position: absolute;\n top: -16px;\n right: -16px;\n ";return i.style.cssText=o+"\n width: 32px;\n height: 32px;\n border-radius: 50%;\n border: none;\n background: #000000;\n color: #ffffff;\n cursor: pointer;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n transition: all 0.2s ease;\n ",i.addEventListener("mouseenter",(()=>{i.style.backgroundColor="#333333",i.style.transform="scale(1.1)"})),i.addEventListener("mouseleave",(()=>{i.style.backgroundColor="#000000",i.style.transform="scale(1)"})),i.addEventListener("click",(e=>{e.stopPropagation(),this.dispatchEvent("overlay-close",{widgetId:this.widgetId})})),i}createCloseSVG(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","16"),e.setAttribute("height","16"),e.setAttribute("viewBox","0 0 16 16"),e.setAttribute("fill","none"),e.style.pointerEvents="none";const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M12 4L4 12M4 4l8 8"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),e.appendChild(t),e}dispatchTriggerEvent(e,t,i){this.dispatchEvent(`trigger-${e}`,{triggerType:t,triggerData:i,mode:this.mode,isInOverlay:this.isInOverlay})}dispatchEvent(e,t){const i=new CustomEvent(`widgetic:${e}`,{detail:Object.assign(Object.assign({widgetId:this.widgetId},t),{source:"trigger-manager"})});document.dispatchEvent(i)}updateConfig(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)})),te.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),te.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,te.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 Xr=Object.freeze({__proto__:null,TriggerManager:Gr});class Yr{constructor(e={}){var t,i;this.widgets=new Map,this.widgetConfigs=new Map,this.compositionData=new Map,this.triggerManagers=new Map,this.compositionWidgets=new Map,this.eventListeners=new Map,this.errorHandlers=new Set,this.isInitialized=!1,this.responsiveState=null,this.config=Object.assign(Object.assign({},e),{security:Object.assign({enableSanitization:!0,enableRateLimit:!0,enableBotDetection:!0},e.security)}),this.apiConfig=new re(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 Vi(this.apiConfig),this.compositionsApi=new Ni(this.apiConfig),this.securityManager=Wr.getInstance(this.config.security||{}),this.displayManager=new Pr,this.performanceMonitor=gr(),this.setupResponsiveTracking(),this.setupEventListeners(),te.info("[WidgetManager] Initialized with config:",{securityEnabled:!!(null===(t=e.security)||void 0===t?void 0:t.enableSanitization),performanceEnabled:!!(null===(i=e.performance)||void 0===i?void 0:i.enabled)})}static getInstance(e){return Yr.instance||(Yr.instance=new Yr(e)),Yr.instance}initialize(){return t(this,void 0,void 0,(function*(){if(this.isInitialized)te.warn("[WidgetManager] Already initialized");else try{this.setupResponsiveTracking(),this.isInitialized=!0,this.emitEvent({type:"manager_initialized",widgetId:"system",timestamp:Date.now()}),te.info("[WidgetManager] Successfully initialized")}catch(e){throw te.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 Gr({widgetId:e,element:n,config:i.triggers});this.triggerManagers.set(e,t),te.debug("[WidgetManager] Trigger manager setup completed:",{widgetId:e,triggers:i.triggers})}catch(t){te.warn("[WidgetManager] Failed to setup trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}return i.compositionId&&this.trackWidgetForComposition(i.compositionId,e),this.widgets.set(e,o),this.widgetConfigs.set(e,i),o.state.ready=!0,te.info("[WidgetManager] Widget registered:",{widgetId:e,compositionId:i.compositionId}),this.emitEvent({type:"widget_registered",widgetId:e,data:{config:i},timestamp:Date.now()}),o}catch(t){throw te.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}}))}trackWidgetForComposition(e,t){this.compositionWidgets.has(e)||this.compositionWidgets.set(e,new Set),this.compositionWidgets.get(e).add(t)}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},en.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},en.CLIENT_URL||"*")}else e.element.dispatchEvent(new CustomEvent("widgetic:data-update",{detail:i}));te.debug("[WidgetManager] Content applied to widget:",{widgetId:e.id,contentType:typeof i})}catch(e){throw te.error("[WidgetManager] Failed to apply content:",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{te.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:br(s)}),a=this.getWidgetsByComposition(e),d=this.compositionData.get(e);let l=i;n.partial&&(null==d?void 0:d.content)&&(l=this.mergeContent(d.content,i));const c={id:e,widgetId:e,content:l,theme:(null==d?void 0:d.theme)||{},version:n.version||(null==d?void 0:d.version)||"1.0.0"};this.compositionData.set(e,c);const u=a.map((i=>t(this,void 0,void 0,(function*(){var t;try{yield this.applyContentToWidget(i,l);const o=null===(t=i.updateHandlers)||void 0===t?void 0:t.get("content");o&&(yield o(l)),i.lastUpdate=Date.now(),te.debug("[WidgetManager] Content applied to widget:",{widgetId:i.id,compositionId:e,source:n.source})}catch(e){throw te.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:l,source:n.source,version:n.version,partial:n.partial},timestamp:Date.now()}),te.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{te.debug("[WidgetManager] Getting widget content schema:",{widgetId:e});const t=yield this.widgetsApi.getWidgetContentSchema({id:e});return te.debug("[WidgetManager] Content schema retrieved:",{widgetId:e,schema:t}),t}catch(t){throw te.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{te.debug("[WidgetManager] Getting widget design schema:",{widgetId:e});const t=yield this.widgetsApi.getWidgetDesignSchema({id:e});return te.debug("[WidgetManager] Design schema retrieved:",{widgetId:e,schema:t}),t}catch(t){throw te.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{te.debug("[WidgetManager] Validating content:",{compositionId:e});const o=yield this.compositionsApi.validateCompositionContent({id:e,body:br(i)});return te.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 te.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),te.info("[WidgetManager] Update handler registered:",{widgetId:e,updateType:t})}unregisterWidget(e){return t(this,void 0,void 0,(function*(){var t;const i=this.widgets.get(e);if(i)try{const n=i.config.compositionId;n&&this.compositionWidgets.has(n)&&(this.compositionWidgets.get(n).delete(e),0===this.compositionWidgets.get(n).size&&this.compositionWidgets.delete(n));try{this.displayManager.cleanup(e),te.debug("[WidgetManager] Display management cleaned up:",{widgetId:e})}catch(t){te.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),te.debug("[WidgetManager] Trigger manager cleaned up:",{widgetId:e})}catch(t){te.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),te.info("[WidgetManager] Widget unregistered:",{widgetId:e,compositionId:n,remainingWidgetsForComposition:(null===(t=this.compositionWidgets.get(n||""))||void 0===t?void 0:t.size)||0}),this.emitEvent({type:"widget_unregistered",widgetId:e,data:{compositionId:n},timestamp:Date.now()})}catch(t){te.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 te.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"===$r().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,te.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){te.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){te.error("[WidgetManager] Event handler failed:",e)}}))}emitError(e){this.errorHandlers.forEach((t=>{try{t(e)}catch(e){te.error("[WidgetManager] Error handler failed:",e)}}))}setupEventListeners(){"undefined"!=typeof window&&document.addEventListener("visibilitychange",(()=>{const e=!document.hidden;this.emitEvent({type:"page_visibility_change",widgetId:"system",data:{visible:e},timestamp:Date.now()})}))}getTriggerManager(e){return this.triggerManagers.get(e)}getAllTriggerManagers(){return new Map(this.triggerManagers)}getStats(){return{widgets:this.widgets.size,compositions:this.compositionWidgets.size,triggerManagers:this.triggerManagers.size,responsiveState:this.responsiveState,isInitialized:this.isInitialized}}destroy(){return t(this,void 0,void 0,(function*(){te.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(),te.debug("[WidgetManager] Trigger manager destroyed:",{widgetId:e})}catch(t){te.warn("[WidgetManager] Failed to destroy trigger manager:",{widgetId:e,error:t instanceof Error?t.message:"Unknown error"})}this.triggerManagers.clear();try{this.displayManager.cleanupAll(),te.debug("[WidgetManager] Display manager cleaned up")}catch(e){te.warn("[WidgetManager] Failed to cleanup display manager:",{error:e instanceof Error?e.message:"Unknown error"})}this.eventListeners.clear(),this.errorHandlers.clear(),this.compositionWidgets.clear(),this.compositionData.clear(),this.isInitialized=!1,this.responsiveState=null,Yr.instance=null,te.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 Jr(e){return Yr.getInstance(e)}Yr.instance=null;var Qr=Object.freeze({__proto__:null,WidgetManager:Yr,getWidgetManager:Jr});const Zr="widgetic_session_id",ea=new Map;let ta=null;function ia(e){var t;try{const t=localStorage.getItem(e);if(null!==t)return t}catch(e){}return null!==(t=ea.get(e))&&void 0!==t?t:null}function na(e,t){ea.set(e,t);try{localStorage.setItem(e,t)}catch(t){ee.debug("localStorage is not available; keeping the A/B test state in memory",{key:e,error:t})}}function oa(e){ea.delete(e);try{localStorage.removeItem(e)}catch(t){ee.debug("localStorage is not available; the value was only forgotten in memory",{key:e,error:t})}}function sa(){const e=ia(Zr);return e||(ta||(ta=function(){try{if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return`visitor_${crypto.randomUUID()}`}catch(e){}return`visitor_${Math.random().toString(36).slice(2,12)}_${Date.now().toString(36)}`}()),na(Zr,ta),ta)}function ra(e,t){return function(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return t>>>0}(`${t}:${e}`)%1e4/100}function aa(e,t){if(!e||!t)return!1;try{return null!==e.closest(t)}catch(e){return ee.warn("The goal target is not a selector this browser understands",{goalTarget:t,error:e}),!1}}class da extends jr{constructor(){super(),this.assignments=new Map,this.conversionSetups=new Map,this.trackedConversions=new Set,this.visitors=new Map;const e=new re({basePath:an()});this.abTestingApi=new qi(e),this.compositionsApi=new Ni(e),this.widgetManager=Yr.getInstance(),this.messenger=new Gs,this.setupEventListeners()}static getInstance(){return da.instance||(da.instance=new da),da.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 ee.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,goalTarget:e.goal_target||e.goalTarget||null}}catch(t){return ee.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 ee.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:n.primary_metric||(null===(i=n.success_metrics)||void 0===i?void 0:i[0])||"impressions"};return ee.info("A/B test config loaded",{experimentId:e,config:s}),s}catch(t){return t&&"object"==typeof t&&"status"in t&&404===t.status?(ee.warn("A/B test not found",{experimentId:e}),null):(ee.error("Failed to load A/B test config",{experimentId:e,error:t}),null)}}))}resolveVisitor(e){return{userId:(null==e?void 0:e.userId)||void 0,sessionId:(null==e?void 0:e.sessionId)||sa()}}visitorFor(e,t){var i;return(null==t?void 0:t.userId)||(null==t?void 0:t.sessionId)?this.resolveVisitor(t):null!==(i=this.visitors.get(e))&&void 0!==i?i:this.resolveVisitor()}readStoredAssignment(e,t){try{const i=ia(`ab_test_${e}`);if(!i)return null;const n=JSON.parse(i),o=t.variants.find((e=>e.id===n.variantId));return o?{variantId:o.id,compositionId:o.compositionId,embedCode:o.embedCode,goalTarget:o.goalTarget,recorded:!0===n.recorded}:(ee.info("Stored A/B test assignment is no longer a version of the test; assigning again",{experimentId:e}),null)}catch(t){return ee.warn("Stored A/B test assignment is unreadable; assigning again",{experimentId:e,error:t}),null}}storeAssignment(e,t){na(`ab_test_${e}`,JSON.stringify(t)),this.assignments.set(e,t)}getVariantAssignment(e,i){return t(this,void 0,void 0,(function*(){try{const t=yield this.getTestConfig(e);if(!t)return null;const n=this.resolveVisitor(i);if(this.visitors.set(e,n),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,goalTarget:i.goalTarget};return this.storeAssignment(e,t),t}}let o=this.readStoredAssignment(e,t);if(!o){const i=this.selectVariant(e,t.variants,n);if(!i)return null;o={variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode,goalTarget:i.goalTarget,recorded:!1},this.storeAssignment(e,o)}if(!o.recorded){(yield this.createAssignment(e,o,n))&&(o=Object.assign(Object.assign({},o),{recorded:!0}),this.storeAssignment(e,o))}return this.assignments.set(e,o),yield this.setupConversionTracking(e,t,o),o}catch(t){return ee.error("Failed to get variant assignment",{experimentId:e,error:t}),null}}))}setupConversionTracking(e,i,n){return t(this,void 0,void 0,(function*(){var t,o,s;try{const r=[i.primaryMetric],a=yield this.findTrackingTargets(n.compositionId,r),d={experimentId:e,variantId:n.variantId,metrics:r,trackingTargets:a,primaryMetric:i.primaryMetric,goalTarget:null!==(t=n.goalTarget)&&void 0!==t?t:null,widgetReportsGoals:null!==(s=null===(o=this.conversionSetups.get(e))||void 0===o?void 0:o.widgetReportsGoals)&&void 0!==s&&s};this.conversionSetups.set(e,d),ee.debug("Conversion tracking setup complete",{experimentId:e,trackedMetrics:r,trackingTargets:a})}catch(t){ee.error("Failed to setup conversion tracking",{experimentId:e,error:t})}}))}getPrimaryMetric(e){var t,i;return null!==(i=null===(t=this.conversionSetups.get(e))||void 0===t?void 0:t.primaryMetric)&&void 0!==i?i:null}setWidgetReportsGoals(e,t){const i=this.conversionSetups.get(e);i&&(i.widgetReportsGoals=t,ee.debug("Widget goal reporting capability set",{experimentId:e,widgetReportsGoals: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 ee.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)),ee.debug("Widget conversion tracking setup",{widgetId:e,experimentId:t})}catch(i){ee.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))}))}conversionKeyFor(e,t){return`ab_converted_${e}_${t.userId||t.sessionId}`}trackConversion(e,i,n,o,s){return t(this,void 0,void 0,(function*(){const t=this.conversionSetups.get(e),r=this.visitorFor(e,s),a=this.conversionKeyFor(e,r);let d=!1;try{if(!t)return void ee.warn("Conversion ignored: the test has no assignment in this page yet",{experimentId:e,conversionType:n});if(n!==t.primaryMetric)return void ee.debug("Conversion ignored: not the goal this test measures",{experimentId:e,conversionType:n,primaryMetric:t.primaryMetric});const s=null==o?void 0:o.goalTarget;if(t.goalTarget&&t.widgetReportsGoals&&s!==t.goalTarget)return void ee.debug("Conversion ignored: not the element this version measures",{experimentId:e,goalTarget:t.goalTarget,reportedGoalTarget:s});if(this.trackedConversions.has(a)||"1"===ia(a))return ee.debug("Conversion already tracked for this visitor",{experimentId:e,variantId:i,conversionType:n}),void this.trackedConversions.add(a);this.trackedConversions.add(a),d=!0;const l={event_type:"conversion",data:br({experimentId:e,variantId:t.variantId||i,userId:r.userId,sessionId:r.sessionId,conversionType:n,goalTarget:t.goalTarget||void 0,timestamp:(new Date).toISOString()})};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:l}),na(a,"1"),this.emit("conversion",{experimentId:e,variantId:i,conversionType:n,data:o}),ee.info("Conversion tracked",{experimentId:e,variantId:i,conversionType:n,data:o})}catch(t){d&&this.trackedConversions.delete(a),ee.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=this.visitorFor(e,n),o={event_type:"impression",data:br({experimentId:e,variantId:i,userId:t.userId,sessionId:t.sessionId,timestamp:(new Date).toISOString()})};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:o}),ee.debug("Impression tracked",{experimentId:e,variantId:i})}catch(t){ee.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 ee.info("Goal tracking validation completed",{variants:e.length,successMetrics:i,issues:t.length,isValid:o}),{isValid:o,issues:t,recommendations:n}}catch(e){return ee.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){ee.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){ee.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,i){return function(e,t,i){if(!e||0===e.length)return null;const n=ra(t,i);let o=0;for(const t of e)if(o+=Number(t.trafficPercentage)||0,n<o)return t;return e[e.length-1]}(t,i.userId||i.sessionId,e)}createAssignment(e,i,n){return t(this,void 0,void 0,(function*(){try{const t="undefined"!=typeof navigator?navigator.userAgent:void 0,o=br({experimentId:e,variantId:i.variantId,userId:n.userId,sessionId:n.sessionId,userAgent:t,deviceType:this.detectDeviceType(t)});return yield this.abTestingApi.createABTestAssignment({createABTestAssignmentRequest:o}),ee.debug("Assignment created in backend",{experimentId:e,variantId:i.variantId}),!0}catch(t){return ee.error("Failed to create assignment in backend",{experimentId:e,error:t}),!1}}))}generateEmbedCode(e){return`<widgetic-widget composition-id="${e}"></widgetic-widget>`}getSessionId(){return sa()}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"}}da.instance=null;var la=Object.freeze({__proto__:null,ABTestManager:da});class ca{static analyzeElement(e){try{const t=this.getExplicitMetadata(e);return t||this.analyzeHeuristically(e)}catch(e){return null}}static getExplicitMetadata(e){const t=e.getAttribute("data-widget-meta");if(t)try{return JSON.parse(t)}catch(e){}const i=e.getAttribute("data-capabilities");if(i)return this.parseCapabilitiesString(i);const n=e.querySelector('script[type="application/json"]');if(n&&n.textContent)try{const e=JSON.parse(n.textContent);return e.capabilities||e.metadata}catch(e){}return null}static analyzeHeuristically(e){const t={type:"custom",version:"1.0.0"},i=e.getAttribute("data-widget-type")||e.getAttribute("data-type")||this.inferTypeFromStructure(e);switch(i&&(t.type=i),t.type){case"media":t.mediaCapabilities=this.analyzeMediaCapabilities(e);break;case"gallery":t.contentCapabilities=this.analyzeContentCapabilities(e);break;case"form":t.textCapabilities=this.analyzeTextCapabilities(e);break;case"interactive":t.interactionCapabilities=this.analyzeInteractionCapabilities(e)}return t.supportsResponsive=this.checkResponsiveSupport(e),t.supportsAutoscale=this.checkAutoscaleSupport(e),t.supportsThemes=this.checkThemeSupport(e),t.displayCapabilities=this.analyzeDisplayCapabilities(e),t.abTestingCapabilities=this.analyzeABTestingCapabilities(e),t}static inferTypeFromStructure(e){var t;return e.querySelector("video, audio")||e.classList.contains("media-widget")||(null===(t=e.getAttribute("data-widget-id"))||void 0===t?void 0:t.includes("video"))?"media":e.querySelector("form, input, textarea")||e.classList.contains("form-widget")?"form":e.querySelector(".gallery, .carousel")||e.classList.contains("gallery-widget")||e.querySelectorAll("img").length>1?"gallery":e.querySelector("button, .interactive")||e.classList.contains("quiz-widget")||e.classList.contains("poll-widget")?"interactive":"custom"}static analyzeMediaCapabilities(e){const t=e.querySelectorAll("video"),i=e.querySelectorAll("audio"),n=null!==e.querySelector("[controls]"),o=null!==e.querySelector("[data-volume], .volume-control");let s="audio";return t.length>0&&i.length>0?s="mixed":t.length>0&&(s="video"),{supportsPlay:!0,supportsPause:!0,supportsVolumeControl:o||n,supportsSeek:n,supportsGlobalVolume:e.hasAttribute("data-global-volume"),mediaType:s}}static analyzeContentCapabilities(e){const t=e.querySelectorAll(".item, .slide, img, .content-item"),i=null!==e.querySelector(".nav, .navigation, button"),n=e.hasAttribute("data-position")||e.hasAttribute("data-track-position");let o="gallery";return e.classList.contains("carousel")&&(o="carousel"),e.classList.contains("list")&&(o="list"),e.classList.contains("grid")&&(o="grid"),{supportsPositionTracking:n,supportsNavigation:i,contentType:o,totalItems:t.length}}static analyzeTextCapabilities(e){const t=e.querySelectorAll("input, textarea, select"),i=Array.from(t).map((e=>e.getAttribute("name")||e.getAttribute("id")||"unknown"));return{supportsTextPersistence:e.hasAttribute("data-persist")||e.hasAttribute("data-autosave"),supportsSanitization:!0,fields:i}}static analyzeInteractionCapabilities(e){const t=e.querySelectorAll("button").length>0,i=e.querySelectorAll("form").length>0,n=e.hasAttribute("data-events")||e.hasAttribute("data-track-interactions"),o=[],s=e.getAttribute("data-events");return s&&o.push(...s.split(",").map((e=>e.trim()))),{supportsClicks:t||null!==e.querySelector("[onclick]"),supportsFormSubmission:i,supportsCustomEvents:n,customEventTypes:o.length>0?o:void 0}}static analyzeDisplayCapabilities(e){return{supportsFullscreen:e.hasAttribute("data-fullscreen")||e.classList.contains("fullscreen-capable"),supportsOverlay:e.hasAttribute("data-overlay")||e.classList.contains("overlay-capable"),supportsPopup:e.hasAttribute("data-popup")||e.classList.contains("popup-capable"),supportsInline:!0}}static analyzeABTestingCapabilities(e){if(!("widgetic-abtest"===e.tagName.toLowerCase()||e.hasAttribute("experiment-id")||e.hasAttribute("data-ab-test")))return;const t=[],i=[];return e.querySelector("button, a, [onclick]")&&(t.push("clicks"),i.push("clicks")),e.querySelector("form")&&(t.push("submissions"),i.push("conversions")),e.querySelector("video, audio")&&(t.push("plays"),i.push("plays")),t.push("impressions"),{supportsTracking:!0,trackableEvents:t,conversionGoals:i}}static checkResponsiveSupport(e){return e.hasAttribute("data-responsive")||e.hasAttribute("data-breakpoints")||e.classList.contains("responsive")}static checkAutoscaleSupport(e){return e.hasAttribute("data-autoscale")||e.hasAttribute("data-auto-height")||e.classList.contains("autoscale")}static checkThemeSupport(e){return e.hasAttribute("data-theme")||e.classList.contains("themeable")||null!==e.querySelector("[data-theme]")}static parseCapabilitiesString(e){const t=e.split(",").map((e=>e.trim()));return{type:"custom",version:"1.0.0",mediaCapabilities:t.includes("media")?{supportsPlay:!0,supportsPause:!0,supportsVolumeControl:t.includes("volume"),supportsSeek:t.includes("seek"),supportsGlobalVolume:t.includes("global-volume"),mediaType:"mixed"}:void 0,textCapabilities:t.includes("forms")?{supportsTextPersistence:t.includes("persist"),supportsSanitization:!0,fields:[]}:void 0,interactionCapabilities:t.includes("interactive")?{supportsClicks:!0,supportsFormSubmission:t.includes("forms"),supportsCustomEvents:t.includes("events")}:void 0,supportsResponsive:t.includes("responsive"),supportsAutoscale:t.includes("autoscale"),supportsThemes:t.includes("themes")}}}function ua(e){var t,i,n,o;const s=new Set;return s.add("rendering"),s.add("api"),e.mediaCapabilities&&s.add("media"),e.textCapabilities&&s.add("security"),e.interactionCapabilities&&s.add("messaging"),((null===(t=e.displayCapabilities)||void 0===t?void 0:t.supportsFullscreen)||(null===(i=e.displayCapabilities)||void 0===i?void 0:i.supportsOverlay)||(null===(n=e.displayCapabilities)||void 0===n?void 0:n.supportsPopup))&&s.add("display"),e.abTestingCapabilities&&(s.add("abTesting"),s.add("messaging")),(null===(o=e.performanceRequirements)||void 0===o?void 0:o.requiresLazyLoading)&&s.add("performance"),Array.from(s)}var ha=Object.freeze({__proto__:null,WidgetMetadataAnalyzer:ca,analyzeWidgetRequirementsEnhanced:function(e){const t=new Set;for(const i of e){const e=ca.analyzeElement(i);if(e){ua(e).forEach((e=>t.add(e)))}}return Array.from(t)},getRequiredChunks:ua});const ga="data-widgetic-overlay",pa="data-device-restricted",ma=new WeakMap,fa=new WeakMap,va=new Map;function ya(e,t,i){if(ma.has(e))return;const n=e.getAttribute("composition-id")||"widget",o=function(e,t){const i=fa.get(e);if(i)return i;const n=(va.get(t)||0)+1;va.set(t,n);const o=1===n?t:`${t}-${n}`;return fa.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 Xr})).then((({TriggerManager:i})=>{if(ma.has(e))return void s();const n=new i({widgetId:o,element:e,config:t,displayWhenShown:"block"});ma.set(e,n),e.hasAttribute(ga)&&e.setAttribute(ga,"armed"),te.debug("[published-host-display] Trigger manager armed",{widgetId:o,mode:t.mode,eventTrigger:t.eventTrigger})})).catch((e=>{s(),te.error("[published-host-display] Could not load the overlay triggers; the embed stays hidden",{widgetId:o,error:e})}))}const wa=/^[A-Za-z0-9_.-]{1,64}$/;function ba(e){return(new TextEncoder).encode(JSON.stringify(e)).length}function Ia(e){if(!e||!e.trim())return null;try{const t=JSON.parse(e);return!t||"object"!=typeof t||Array.isArray(t)?null:t}catch(e){return null}}function ka(e){const t=Ia(e);if(!t)return null;const i=Object.keys(t);if(i.length>50)return null;if(ba(t)>8192)return null;const n={};for(const e of i){if(!wa.test(e))return null;const i=t[e];if("boolean"==typeof i)n[e]=i;else if("number"==typeof i){if(!Number.isFinite(i))return null;n[e]=i}else{if("string"!=typeof i)return null;if(i.length>2e3)return null;n[e]=i}}return n}function Ta(e){if(!(null==e?void 0:e.trim()))return null;const t=e.trim();if(t.length>2048)return null;try{return"https:"!==new URL(t).protocol?null:t}catch(e){return null}}const Sa=new WeakMap;function Ca(e){var t;const i=e.getAttribute("context"),n=function(e){const t=Ia(e);if((null==e?void 0:e.trim())&&!t)return{value:null,invalid:!0};if(!t)return{value:null,invalid:!1};const i=Object.keys(t);if(i.length>20)return{value:null,invalid:!0};if(ba(t)>2048)return{value:null,invalid:!0};const n={};for(const e of i){if(!wa.test(e))return{value:null,invalid:!0};const i=t[e];if("number"==typeof i){if(!Number.isFinite(i))return{value:null,invalid:!0};n[e]=i}else{if("string"!=typeof i)return{value:null,invalid:!0};if(i.length>500)return{value:null,invalid:!0};n[e]=i}}return{value:n,invalid:!1}}(i);return n.invalid&&function(e,t){const i=null!=t?t:"";let n=Sa.get(e);n||(n=new Set,Sa.set(e,n)),n.has(i)||n.add(i)}(e,i),{context:n.invalid?null:n.value,contextInvalid:n.invalid,values:ka(e.getAttribute("values")),mediaResolver:Ta(null!==(t=e.getAttribute("media-resolver"))&&void 0!==t?t:e.getAttribute("mediaresolver"))}}const Aa="data-widgetic-context-invalid";let Ea=e=>import(e);function Ra(e){try{return Ea(e).then((()=>!0),(()=>!1))}catch(e){return Promise.resolve(!1)}}const xa=new WeakMap,Ma=new WeakMap;function Wa(e,t){t?Ma.set(e,t):Ma.delete(e);const i=xa.get(e);if(i)try{i.instance.update(Da(e,i.payload))}catch(e){}}function Oa(e){const t=xa.get(e);if(t){xa.delete(e);try{t.instance.destroy()}catch(e){}t.stop()}for(const t of Array.from(e.querySelectorAll("[data-widgetic-direct]")))t.remove()}function Da(e,t){const i=Ca(e);i.contextInvalid?e.setAttribute(Aa,""):e.removeAttribute(Aa);const n=Ss(e,t),o=Object.assign(Object.assign(Object.assign({},t.content||{}),n.content),i.values||{}),s=Object.assign(Object.assign({},t.design||{}),n.design),r=n.contentItems&&n.contentItems.length>0?n.contentItems:t.contentItems||[],a=Ma.get(e);return Object.assign(Object.assign({design:s,content:o,contentItems:r,context:i.context,mediaResolver:i.mediaResolver},t.entries?{entries:t.entries}:{}),a?{workflow:a}:{})}function La(e,i,n,o){return t(this,void 0,void 0,(function*(){ds(e);const t=ls(e)||"",s=i.direct;if(!s||2!==s.contractVersion||!s.moduleUrl)return!1;let r;try{r=yield Ea(s.moduleUrl)}catch(e){return!1}if(!e.isConnected||(ls(e)||"")!==t)return!1;if(2!==r.contractVersion)return!1;Oa(e);const a=document.createElement("div");a.setAttribute("data-widgetic-direct","1"),a.setAttribute("width",n||e.getAttribute("width")||"400");const d=e.getAttribute("height");d&&a.setAttribute("height",d);const l=a.attachShadow({mode:"open"}),c=document.createElement("style");c.textContent=r.getStyles();const u=document.createElement("div");u.className="widgetic-direct-target",l.append(c,u);const h={compositionId:t,payload:i,instance:null,stop:()=>{}},g=r.mount(u,Da(e,h.payload));h.instance=g;const p=function(e,t,i){const n="undefined"!=typeof MutationObserver?MutationObserver:null;if(!n)return()=>{};let o;try{o=new n((n=>{As(n)&&i.update(Da(e,t()))}))}catch(e){return()=>{}}return o.observe(e,{attributes:!0,childList:!0,subtree:!0,characterData:!0}),()=>o.disconnect()}(e,(()=>h.payload),g),m=["play","pause","ended","seeking","seeked","timeupdate","progress","volumechange","trackchange","playlistchange"],f=["position","navigate","complete","reset","metadata"],v=[];let y=!1,w=0;for(const i of m){const n=`widgetic:media:${i}`,o=e=>{if(y)return;const n=e,o=n.detail&&"object"==typeof n.detail?n.detail:{};try{zs().handleMediaEvent({type:i,compositionId:t,config:{persistState:!0,autoResume:!0},data:o})}catch(e){}};u.addEventListener(n,o),e.addEventListener(n,o),v.push((()=>{u.removeEventListener(n,o),e.removeEventListener(n,o)}))}const b=["play","pause","timeupdate","seeking","volumechange","ended"];for(const e of b){const i=i=>{if(y)return;const n=i.target;if(!n||"AUDIO"!==n.tagName&&"VIDEO"!==n.tagName)return;if("pause"===e&&n.ended)return;if("timeupdate"===e){const e=Date.now();if(e-w<750)return;w=e}const o="VIDEO"===n.tagName?"video":"audio";try{zs().handleMediaEvent({type:e,compositionId:t,config:{mediaType:o,persistState:!0,autoResume:!0},data:{mediaType:o,position:n.currentTime||0,duration:Number.isFinite(n.duration)?n.duration:void 0,volume:n.muted?0:n.volume,playing:!n.paused}})}catch(e){}};u.addEventListener(e,i,!0),v.push((()=>{u.removeEventListener(e,i,!0)}))}const I=e=>{const t=e.detail;if(!t||"object"!=typeof t)return;const i=Array.from(u.querySelectorAll("audio, video")),n=i.find((e=>!e.paused))||i[0]||null;y=!0;try{if("pause"===t.command)for(const e of i){if("number"==typeof t.position&&!Number.isNaN(t.position)&&t.position>=0)try{e.currentTime=t.position}catch(e){}try{e.pause()}catch(e){}}else if("play"===t.command){if(n){if("number"==typeof t.position&&!Number.isNaN(t.position)&&t.position>=0)try{n.currentTime=t.position}catch(e){}try{const e=n.play();e&&"function"==typeof e.catch&&e.catch((()=>{}))}catch(e){}}}else if("restore"===t.command&&t.state){if(n&&("number"==typeof t.state.volume&&(n.volume=Math.max(0,Math.min(1,t.state.volume))),"number"==typeof t.state.position&&!Number.isNaN(t.state.position)&&t.state.position>=0))try{n.currentTime=t.state.position}catch(e){}}else if("setVolume"===t.command&&"number"==typeof t.volume){const e=Math.max(0,Math.min(1,t.volume));for(const t of i)t.volume=e}}finally{setTimeout((()=>{y=!1}),150)}};u.addEventListener("widgetic:media:command",I),v.push((()=>{u.removeEventListener("widgetic:media:command",I)}));for(const i of f){const n=`widgetic:content:${i}`,o=e=>{const n=e,o=n.detail&&"object"==typeof n.detail?n.detail:{};try{$s().handleContentPositionEvent({type:i,compositionId:t,config:{contentType:"custom",persistState:!0,autoResume:!0},data:o})}catch(e){}};u.addEventListener(n,o),e.addEventListener(n,o),v.push((()=>{u.removeEventListener(n,o),e.removeEventListener(n,o)}))}h.stop=()=>{p();for(const e of v)e()},xa.set(e,h),e.appendChild(a),o(e);try{$s().resumeWidgetPosition(t)}catch(e){}try{zs().resumeWidget(t)}catch(e){}return e.dispatchEvent(new CustomEvent("widgetic:ready",{bubbles:!0,composed:!0,detail:{compositionId:t}})),!0}))}const Ua=new WeakMap;function Pa(e,t){_a(e),Ua.set(e,t)}function _a(e){const t=Ua.get(e);if(!t)return!1;Ua.delete(e);try{t.stop()}catch(e){te.debug("[workflows] A workflow failed while it was being stopped",{error:e})}return!0}const za="data-widgetic-refused",qa="data-widgetic-context-invalid",ja="data-widgetic-composition-tracked";function Ba(e,t){const i=e.getAttribute(ja);if(i&&i!==t){_a(e),function(e){e.removeAttribute("data-widgetic-mounting"),e.removeAttribute("data-widgetic-mounted"),e.removeAttribute(pa),e.removeAttribute(za),e.removeAttribute(qa)}(e),Oa(e);for(const t of Array.from(e.querySelectorAll("iframe")))t.remove();e.style.display="",e.removeAttribute("data-widgetic-overlay")}e.setAttribute(ja,t)}const $a=/^[a-z][a-z0-9_]{0,62}$/,Na=/^[a-z][a-z0-9_]{0,39}$/;function Fa(e){if(e.length>200)return null;const t=e.indexOf("@");if(-1===t)return/^[a-z][a-z0-9_]{0,31}$/.test(e)?{metric:e,selector:null}:null;const i=e.slice(0,t),n=e.slice(t+1);return/^[a-z][a-z0-9_]{0,31}$/.test(i)&&""!==n&&n===n.trim()?{metric:i,selector:n}:null}function Ka(e){if(e.length>200)return!1;const t=e.indexOf("@"),i=-1===t?e:e.slice(0,t);return!!Na.test(i)&&(-1===t||""!==e.slice(t+1))}function Ha(e){const t=[],i=[],n=[],o=e=>{t.length<20&&$a.test(e)&&!t.includes(e)&&t.push(e)};for(const t of e.inputTables)o(t);for(const t of e.inputColumns){if(i.length>=50)break;$a.test(t.table)&&$a.test(t.column)&&(i.some((e=>e.table===t.table&&e.column===t.column))||(i.push({table:t.table,column:t.column}),o(t.table)))}for(const t of e.actionIds){if(n.length>=20)break;Ka(t)&&!n.includes(t)&&n.push(t)}return{tables:t,fields:i,goals:n}}function Va(e,t){const i=[];for(const e of t.goals){const t=Fa(e);t&&i.push({id:e,metric:t.metric,goalTarget:t.selector})}return{compositionId:e,tables:t.tables,fields:t.fields,goals:i}}const Ga=["context","values","media-resolver"],Xa=new Set(["widgetic:ready","widgetic:error","widgetic:submitted","widgetic:resize","widgetic:data","widgetic:interaction","widgetic:form-submit","widgetic:goal"]);const Ya=new WeakMap;class Ja{constructor(e,t,i,n){this.host=e,this.iframe=t,this.gatewayOrigin=i,this.compositionId=n,this.readyDispatched=!1,this.latestAbGoal=null,this.latestWorkflowWatch=null,this.attributeFlushScheduled=!1,this.attributeObserver=null,ds(this.host),this.onWindowMessage=e=>this.handleWrapperMessage(e),window.addEventListener("message",this.onWindowMessage),this.iframe.addEventListener("load",(()=>this.postHostSnapshot())),this.observeHostAttributes()}observeHostAttributes(){const e="undefined"!=typeof MutationObserver?MutationObserver:null;if(!e)return;let t;try{t=new e((e=>{e.some((e=>"attributes"===e.type&&e.attributeName&&Ga.includes(e.attributeName)))&&this.scheduleHostSnapshot()}))}catch(e){return}t.observe(this.host,{attributes:!0,attributeFilter:[...Ga]}),this.attributeObserver=t}scheduleHostSnapshot(){this.attributeFlushScheduled||(this.attributeFlushScheduled=!0,queueMicrotask((()=>{this.attributeFlushScheduled=!1,this.postHostSnapshot()})))}postHostSnapshot(){try{const e=Ca(this.host);e.contextInvalid?this.host.setAttribute(qa,"1"):this.host.removeAttribute(qa);const t=this.iframe.contentWindow;if(!t)return;const i=function(e,t){return{type:"widgetic:host",version:1,compositionId:e,context:t.context,values:t.values,mediaResolver:t.mediaResolver}}(this.compositionId,e);t.postMessage(i,this.gatewayOrigin),this.postAbGoal(),this.postWorkflowWatch()}catch(e){}}sendAbGoal(e){this.latestAbGoal=e,this.postAbGoal()}postAbGoal(){if(this.latestAbGoal)try{const e=this.iframe.contentWindow;if(!e)return;e.postMessage({type:"widgetic:ab-goal",compositionId:this.compositionId,metric:this.latestAbGoal.metric,goalTarget:this.latestAbGoal.goalTarget},this.gatewayOrigin)}catch(e){}}sendWorkflowWatch(e){this.latestWorkflowWatch=e,this.postWorkflowWatch()}postWorkflowWatch(){var e,t;if(this.latestWorkflowWatch)try{const i=this.iframe.contentWindow;if(!i)return;i.postMessage((e=this.compositionId,t=this.latestWorkflowWatch,{type:"widgetic:workflow-watch",version:1,compositionId:e,tables:t.tables,fields:t.fields,goals:t.goals}),this.gatewayOrigin)}catch(e){}}sendWidgetUpdate(e){try{const t=this.iframe.contentWindow;if(!t)return;t.postMessage(Object.assign(Object.assign(Object.assign({type:"widgetic:update",compositionId:this.compositionId},e.design?{design:e.design}:{}),e.content?{content:e.content}:{}),e.contentItems?{contentItems:e.contentItems}:{}),this.gatewayOrigin)}catch(e){}}handleWrapperMessage(e){var t,i;if(e.source!==this.iframe.contentWindow)return;if(e.origin!==this.gatewayOrigin)return;const n=e.data;if(!n||"object"!=typeof n||Array.isArray(n))return;const o=n.type;if("string"!=typeof o)return;const s=n.compositionId;if("string"==typeof s&&s!==this.compositionId)return;let r=null!==(i=null!==(t=n.detail)&&void 0!==t?t:n.payload)&&void 0!==i?i:n.data;if(void 0===r){const e={};for(const t of Object.keys(n))"type"!==t&&"compositionId"!==t&&(e[t]=n[t]);Object.keys(e).length>0&&(r=e)}const a=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};try{const t=JSON.stringify(e);return(new TextEncoder).encode(t).length>8192?{}:e}catch(e){return{}}}(r),d=Object.assign({compositionId:this.compositionId},a);if(o.startsWith("widgetic:media:")){const e=o.replace("widgetic:media:","");try{zs().handleMediaEvent({type:e,compositionId:this.compositionId,config:{persistState:!0,autoResume:!0},data:a})}catch(e){}this.dispatchHostEvent(o,d)}else if(o.startsWith("widgetic:content:")){const e=o.replace("widgetic:content:","");try{$s().handleContentPositionEvent({type:e,compositionId:this.compositionId,config:{contentType:"custom",persistState:!0,autoResume:!0},data:a})}catch(e){}this.dispatchHostEvent(o,d)}else if(Xa.has(o))if("widgetic:ready"!==o)this.dispatchHostEvent(o,d);else{try{$s().resumeWidgetPosition(this.compositionId)}catch(e){}try{zs().resumeWidget(this.compositionId)}catch(e){}if(this.readyDispatched)return;this.readyDispatched=!0,this.postHostSnapshot();const e=function(e){const t=e.capabilities;return Array.isArray(t)?t.filter((e=>"string"==typeof e&&e.length<=40)).slice(0,32):[]}(a);this.dispatchHostEvent("widgetic:ready",Object.assign({compositionId:this.compositionId},e.length>0?{capabilities:e}:{}))}}dispatchHostEvent(e,t){this.host.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}destroy(){var e;window.removeEventListener("message",this.onWindowMessage),null===(e=this.attributeObserver)||void 0===e||e.disconnect(),this.attributeObserver=null}}function Qa(e){return Ya.get(e)}function Za(e,t,i){e.dispatchEvent(new CustomEvent("widgetic:error",{detail:{compositionId:t,code:i},bubbles:!0,composed:!0}))}const ed="__widgeticEmbedSharedServices",td="__widgeticEmbedWorkflows",id=/^[A-Za-z0-9_.:-]{1,64}$/,nd=new Set(["__proto__","constructor","prototype"]);function od(e){return"string"==typeof e?e.length>200?e.slice(0,200):e:"number"==typeof e?Number.isFinite(e)?e:void 0:"boolean"==typeof e?e:void 0}function sd(e){if("object"!=typeof e||null===e||Array.isArray(e))return null;const{name:t,values:i}=e;if("string"!=typeof t||!id.test(t))return null;const n={};if("object"==typeof i&&null!==i&&!Array.isArray(i)){let e=0;for(const t of Object.keys(i)){if(e>=12)break;if(nd.has(t)||!id.test(t))continue;const o=od(i[t]);void 0!==o&&(n[t]=o,e+=1)}}return{name:t,values:n}}class rd{constructor(){this.events=[]}add(e){this.events.push(e),this.events.length>20&&this.events.shift()}take(){const e=this.events;return this.events=[],e}clear(){this.events=[]}}const ad="https://cdn.widgetic.com/sdks/browser/embed-sdk-workflows.js",dd=/(^|\/)embed-sdk(\.min)?\.js$/;function ld(e){return{source:e.src,explicitSource:e.getAttribute("data-workflows-src"),nonce:e.nonce||null}}const cd="undefined"!=typeof document&&"undefined"!=typeof HTMLScriptElement&&document.currentScript instanceof HTMLScriptElement?document.currentScript:null;function ud(){return t(this,void 0,void 0,(function*(){var e;const t=window,i=function(){if(cd)return ld(cd);if("undefined"==typeof document)return null;for(const e of Array.from(document.querySelectorAll("script[src*='embed-sdk']")))try{if(dd.test(new URL(e.src).pathname))return ld(e)}catch(e){}return null}(),n=function(e,t){if(!e)return ad;try{if(e.explicitSource)return new URL(e.explicitSource,t).href;const i=new URL(e.source,t),n=i.pathname.replace(dd,"$1embed-sdk-workflows$2.js");if(n!==i.pathname)return i.pathname=n,i.hash="",i.href}catch(e){te.debug("[workflows] The address of the workflow code could not be worked out from the SDK's script, so the default is used",{error:e})}return ad}(i,document.baseURI);te.debug("[workflows] Loading the workflow code",{url:n}),Object.defineProperty(t,ed,{value:{contractVersion:1,abVisitor:{elementMatchesGoalTarget:aa,readStoredValue:ia,removeStoredValue:oa,writeStoredValue:na},autoscaleManager:{readStoredAutoscaleHeight:Ds,writeStoredAutoscaleHeight:Ls},declarativeEmbedParser:{declarativeChildrenOf:hs,isReservedHostAttribute:gs},hostBridgeMarkers:{REFUSED_HOST_ATTRIBUTE:za},hostWorkflowWatch:{buildWorkflowWatch:Ha,splitActionId:Fa,workflowWatchProperty:Va},logger:{log:te},mountDirectWidget:{setDirectMountWorkflow:Wa,warmDirectModule:Ra},publicEmbedLookup:{publicEmbedApiOrigins:Xo,resolvePublishedEmbed:Jo},publishedHostBridge:{dispatchPublishedHostError:Za,getPublishedHostBridge:Qa},publishedHostDisplay:{OVERLAY_HOST_ATTRIBUTE:ga},workflowEmbedRegistry:{registerWorkflowEmbed:Pa},workflowPageEvents:{PageEventQueue:rd,readPageEvent:sd,WORKFLOW_EVENT_TYPE:"widgetic:workflow-event",WORKFLOW_STEP_EVENT_TYPE:"widgetic:workflow-step"}},configurable:!0});try{return yield function(e,t){return new Promise(((i,n)=>{const o=document.createElement("script");o.async=!0,o.src=e,t&&(o.nonce=t),o.setAttribute("data-widgetic-workflow-code","");const s=setTimeout((()=>{r(),n(new Error(`The workflow code did not arrive within 20 seconds (${e})`))}),2e4);function r(){clearTimeout(s),o.onload=null,o.onerror=null,o.remove()}o.onload=()=>{r(),i()},o.onerror=()=>{r(),n(new Error(`The workflow code could not be loaded (${e})`))},(document.head||document.documentElement).appendChild(o)}))}(n,null!==(e=null==i?void 0:i.nonce)&&void 0!==e?e:null),function(e){const t=e[td];if(!t||"function"!=typeof t.startWorkflowEmbed)throw new Error("The workflow code was loaded but did not offer itself, so it did not run (a script error, or another file under that address)");if(1!==t.contractVersion)throw new Error(`The workflow code is from another release of the SDK (it works with version ${String(t.contractVersion)} of the hand-over, this SDK with version 1)`);return{startWorkflowEmbed:t.startWorkflowEmbed}}(t)}finally{delete t[ed],delete t[td]}}))}let hd=null,gd=null;function pd(e){e.setAttribute("data-widgetic-mounted","1"),e.removeAttribute("data-widgetic-mounting"),e.hasAttribute(ga)||(e.style.display="block")}function md(e,t,i,n){pd(e);const o=ls(e),s=Cs(e,i),r=ts(t,n||e.getAttribute("width")||"400",e.getAttribute("height")||"300",o||void 0,s);if(e.appendChild(r),o)try{!function(e,t,i,n){let o;try{o=new URL(i).origin}catch(e){return}const s=Ya.get(e);s&&s.destroy();const r=new Ja(e,t,o,n);Ya.set(e,r),r.postHostSnapshot()}(e,r,t,o)}catch(e){}try{!function(e,t,i){const n=Es.get(e);n&&n();const o="undefined"!=typeof MutationObserver?MutationObserver:null;if(!o)return()=>{};let s,r=!1;try{s=new o((n=>{As(n)&&(r||(r=!0,queueMicrotask((()=>{r=!1;const n=Ss(e,t);i(n)}))))}))}catch(e){return()=>{}}s.observe(e,{attributes:!0,childList:!0,subtree:!0,characterData:!0});const a=()=>{s.disconnect(),Es.delete(e)};Es.set(e,a)}(e,i,(t=>{const i=Qa(e);if(i)i.sendWidgetUpdate({design:t.design,content:t.content,contentItems:t.contentItems});else if(r.contentWindow)try{r.contentWindow.postMessage(Object.assign(Object.assign(Object.assign({type:"widgetic:update"},t.design?{design:t.design}:{}),t.content?{content:t.content}:{}),t.contentItems?{contentItems:t.contentItems}:{}),"*")}catch(e){}}))}catch(e){}}function fd(e,t,i){var n;const o=ls(e)||"",s=Cs(e,t);("iframe"===e.getAttribute("render-mode")||"true"===e.getAttribute("use-iframe")||!e.getAttribute("composition-id")&&Boolean(o)&&!(null===(n=s.direct)||void 0===n?void 0:n.moduleUrl))&&s.embedUrl?md(e,s.embedUrl,s,i):La(e,s,i,pd).then((t=>{t||e.isConnected&&(ls(e)||"")===o&&(e.getAttribute("data-widgetic-mounted")||wd(e,o,"REPUBLISH_REQUIRED","republish_required"))}))}function vd(e){if(!e.hasAttribute("workflow-id"))return null;try{return(hd||(gd&&Date.now()-gd.at<6e4?Promise.reject(gd.error):(hd=ud().then((e=>(gd=null,e)),(e=>{throw hd=null,gd={at:Date.now(),error:e instanceof Error?e:new Error(String(e))},gd.error})),hd))).catch((e=>(te.warn("[workflows] The workflow code could not be loaded, so the tag is embedded as it is",{error:e}),null)))}catch(e){return te.warn("[workflows] The workflow code could not be loaded, so the tag is embedded as it is",{error:e}),Promise.resolve(null)}}function yd(e,t,i,n){i?i.then((i=>{var o;if(!e.isConnected||e.getAttribute("data-widgetic-mounted"))return;let s=null;try{s=null!==(o=null==i?void 0:i.startWorkflowEmbed(e,Object.assign({hydrate:e=>{bd(e)},markMounted:pd},n?{width:n}:{})))&&void 0!==o?o:null}catch(e){te.warn("[workflows] The workflow could not start, so the tag is embedded as it is",{error:e})}s||fd(e,t,n)})):fd(e,t,n)}function wd(e,t,i,n){e.removeAttribute("data-widgetic-mounting"),e.setAttribute(za,i),Za(e,t,n)}function bd(e){var t;ds(e);const i=rs(e),n=null!==(t=null==i?void 0:i.id)&&void 0!==t?t:null;if(ks(e),n&&Ba(e,n),e.getAttribute("data-widgetic-mounted")||e.getAttribute("data-widgetic-mounting")||e.getAttribute(pa)||e.getAttribute(za))return!0;const o=e.getAttribute("src");if(o)return md(e,o),!0;if(!i||!n)return!1;const s=e.hasAttribute(pa),r=function(e){var t,i,n,o,s;let r;try{r=Cn(e)}catch(e){return te.warn("[published-host-display] Could not read the embed's display settings",{error:e}),{suppressed:!1}}return Nr(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(ga,"pending")),{suppressed:!1,triggers:r.triggers}):(e.style.display="none",e.setAttribute(pa,"true"),te.debug("[published-host-display] Embed skipped: this device is switched off",{compositionId:r.compositionId,device:r.device}),{suppressed:!0})}(e);if(r.suppressed)return s||Za(e,n,"device_restricted"),!0;e.setAttribute("data-widgetic-mounting","1");const a="composition"===i.kind?vd(e):null;return("widget"===i.kind?Qo(n):Jo(n)).then((t=>{var i;if(e.getAttribute("data-widgetic-mounted"))return;if("refused"===t.status)return e.removeAttribute("data-widgetic-mounting"),e.setAttribute(za,t.refusal.code),es(n,t.refusal),void Za(e,n,Io(t.refusal.code)||"domain_not_allowed");if("failed"===t.status)return void wd(e,n,t.failure.gatewayCode,t.failure.stateCode);const o="found"===t.status?t.payload:null;if(!(null==o?void 0:o.embedUrl))return e.removeAttribute("data-widgetic-mounting"),void wd(e,n,"NOT_FOUND","not_found");const{triggers:s}=r;if("overlay"!==(null==s?void 0:s.mode))yd(e,o,a),s&&ya(e,s);else{const t=(null===(i=s.overlay)||void 0===i?void 0:i.fullWidth)?"100%":void 0;ya(e,s,(()=>yd(e,o,a,t)))}})),!0}function Id(e=document){const t=e.querySelectorAll("widgetic, widgetic-embed");let i=0;for(const e of Array.from(t))e instanceof HTMLElement&&bd(e)&&(i+=1);return i}const kd={mobile:480,tablet:768,desktop:1024},Td={MANUAL:"manual",EXIT_INTENT:"exit-intent",ON_SCROLL:"on-scroll",TIME_DELAY:"time-delay",ENGAGEMENT_THRESHOLD:"engagement",EXTERNAL_TRIGGER:"external"},Sd={DEFAULT_ANIMATION:"fade",DEFAULT_DELAY_MS:1e3,SUPPORTED_ANIMATIONS:["fade","slide-up","slide-down","slide-left","slide-right","zoom","bounce"]};class Cd{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:kd.mobile,tablet:kd.tablet,desktop:kd.desktop}),this.isEnabled=this.config.enabled,this.isEnabled&&this.initializeEventListeners(),te.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&&(te.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)),te.info("Overlay displayed",{displayMode:t.displayMode,animation:t.animation,autoClose:t.autoClose}),this.emitOverlayEvent("overlay-shown",t)}catch(t){te.error("Failed to show overlay",{error:t,config:e})}}else te.warn("Overlay manager is disabled")}validateOverlayConfig(e){const t=Object.assign({},e);return t.displayMode&&Object.values(Td).includes(t.displayMode)||(t.displayMode=Td.MANUAL),t.animation&&Sd.SUPPORTED_ANIMATIONS.includes(t.animation)||(t.animation=Sd.DEFAULT_ANIMATION,te.debug("Using default animation for overlay",{provided:e.animation,defaultUsed:Sd.DEFAULT_ANIMATION})),t.delay||(t.delay=Sd.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,te.debug("Overlay hidden"),this.emitOverlayEvent("overlay-hidden",{})}createOverlayElement(e){const t=document.createElement("div");t.className=`widgetic-overlay widgetic-overlay-${e.animation||Sd.DEFAULT_ANIMATION}`,!1!==e.showBackdrop&&t.classList.add("widgetic-overlay-backdrop"),t.innerHTML=`\n <div class="widgetic-overlay-content">\n <button class="widgetic-overlay-close">×</button>\n <div class="widgetic-overlay-body">\n ${e.content}\n </div>\n </div>\n `,this.addOverlayStyles();const i=t.querySelector(".widgetic-overlay-close");i&&(i.setAttribute("aria-label",Vs("close")),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||kd.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||kd.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:Sd.DEFAULT_ANIMATION,delay:Sd.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,te.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),te.debug("OverlayManager destroyed")}}let Ad=null;class Ed{constructor(e={}){this.items=new Map,this.observer=null,this.preloadObserver=null,this.loadingQueue=[],this.activeLoads=0,this.performanceMonitor=gr(),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)),l=e.length>0?d.length/e.length:0;return{totalItems:e.length,loadedItems:t.length,failedItems:i.length,averageLoadTime:o,viewportUtilization:a,preloadSuccess:l}}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 Rd=null;class xd{constructor(e={}){this.resources=new Map,this.loadQueue=[],this.activeRequests=0,this.performanceMonitor=gr(),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 Md=null;function Wd(e){return Md||(Md=new xd(e)),Md}let Od=!1;class Dd{constructor(e={}){var t,i,n,o,s,r,a,d,l,c,u,h,g,p,m,f,v,y,w,b,I,k;this.version=Yi,this.instances=new Map,this.isInitialized=!1,this.renderer=dr(),this.widgetControllers=new Map,this.authDetector=Tr(),this.editorOverlay=xr(),this.displayManager=zr(),this.resizeHandler=(Zs||(Zs=new Qs(k)),Zs),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=to(),this.messenger=Ys(this.config.messagingOptions);const T=this.config.logLevel||(this.config.debug?"debug":"info");if(te.setLevel(T),hn.enabled&&te.info("Initializing EmbedSDK",{version:Yi,config:this.config,browserCapabilities:this.browserCapabilities}),"updateConfig"in this.displayManager&&"function"==typeof this.displayManager.updateConfig&&this.displayManager.updateConfig(this.config.displayOptions||{}),"updateConfig"in this.resizeHandler&&"function"==typeof this.resizeHandler.updateConfig&&this.resizeHandler.updateConfig(this.config.resizeOptions||{}),!1!==(null===(t=this.config.performance)||void 0===t?void 0:t.enabled)){pr(Object.assign({enableTracking:gn.ENABLE_PERFORMANCE_TRACKING,axiomApiKey:gn.AXIOM_API_KEY,axiomDataset:gn.AXIOM_DATASET,axiomApiEndpoint:gn.AXIOM_API_ENDPOINT,statsigKey:gn.STATSIG_API_KEY,statsigApiEndpoint:gn.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={}){Rd=new Ed(e)}((null===(o=this.config.lazyLoading)||void 0===o?void 0:o.config)||{}),void 0!==this.config.debug&&(ee.setDebug(this.config.debug),this.config.debug&&ee.setLevel("debug")),!1!==(null===(s=this.config.resourceOptimization)||void 0===s?void 0:s.enabled)&&function(e={}){Md=new xd(e)}((null===(r=this.config.resourceOptimization)||void 0===r?void 0:r.config)||{}),this.config.editorOptions&&(this.editorOverlay=xr(this.config.editorOptions)),!1!==(null===(a=this.config.overlayConfig)||void 0===a?void 0:a.enabled)&&(this.overlayManager=function(e){return Ad||(Ad=new Cd(e)),Ad}({enabled:!0,defaultMode:null===(d=this.config.overlayConfig)||void 0===d?void 0:d.defaultMode,exitIntentEnabled:null===(l=this.config.overlayConfig)||void 0===l?void 0:l.exitIntentEnabled,scrollTriggerEnabled:null===(c=this.config.overlayConfig)||void 0===c?void 0:c.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}})),te.info("Widgetic Embed SDK v1.0 initialized",{version:Yi,capabilities:this.browserCapabilities,editingEnabled:!1!==this.config.enableEditing,overlayEnabled:null!==this.overlayManager}),this.config.debug&&te.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)te.warn("SDK already initialized");else if(Od||"undefined"!=typeof window&&window.__WIDGETIC_SDK_INITIALIZED__)te.warn("SDK initialization detected, skipping duplicate setup");else try{if(this.isInitialized=!0,Od=!0,"undefined"!=typeof window&&(window.__WIDGETIC_SDK_INITIALIZED__=!0),!1!==this.config.enableEditing&&this.checkAuthentication().catch((e=>{te.warn("Background authentication check failed",{error:e})})),this.config.preloadUISDK&&(null===(e=this.authenticationStatus)||void 0===e?void 0:e.isAuthenticated))try{const e=Ar();yield e.preload(),te.info("UI SDK preloaded successfully")}catch(e){te.warn("Failed to preload UI SDK",{error:e})}yield this.scanPage(),te.info("Widgetic Embed SDK initialized successfully",{version:Yi,capabilities:this.browserCapabilities,authenticationStatus:null===(t=this.authenticationStatus)||void 0===t?void 0:t.isAuthenticated}),yield this.scanPage()}catch(e){throw te.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?te.info("User authenticated for editing",{userId:null===(e=this.authenticationStatus.user)||void 0===e?void 0:e.id}):te.debug("User not authenticated for editing")}catch(e){te.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*(){te.info("Refreshing widgets"),yield this.scanPage()}))}watchPublishedHosts(){Id(),this.hostObserverStarted||"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.hostObserverStarted=!0,new MutationObserver((()=>{Id()})).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(te.debug("Found widgetic host elements",{count:o.length}),0===o.length)return void te.info("No widgets found on page");const s=[];for(const r of Array.from(o))if(Hn(r)&&r instanceof HTMLElement){if(bd(r))continue;try{const o=Cn(r),a=null===(t=null===(e=o.device)||void 0===e?void 0:e.mobileEnabled)||void 0===t||t;if(!Nr(a,null===(n=null===(i=o.device)||void 0===i?void 0:i.desktopEnabled)||void 0===n||n)){te.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){te.error("Failed to parse widget configuration",{element:r.outerHTML,error:e})}}0!==s.length?yield this.renderWidgetsBatch(s):te.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:so(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=Kn(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 l={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(l.id,l),yield this.maybeAddEditorOverlay(o.element,s.compositionId),te.debug("Widget rendered successfully",{instanceId:l.id,compositionId:s.compositionId,renderMode:o.renderMode,displayMode:s.displayMode})}te.info("Batch widget rendering complete",{rendered:n.length,total:e.length})}catch(t){te.error("Batch widget rendering failed",{error:t});for(const{element:t,config:i}of e)try{yield this.renderSingleWidget(t,i)}catch(e){te.error("Individual widget rendering failed",{compositionId:i.compositionId,error:e})}}}))}renderSingleWidget(e,i){return t(this,void 0,void 0,(function*(){try{performance.now(),gr(),Wd();const n=function(e){return Rd||(Rd=new Ed(e)),Rd}();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=gr(),n=e instanceof Error?e.message:"Render failed";throw t.recordWidgetError(i.compositionId,n),t.endWidgetLoad(i.compositionId,!1),te.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=gr(),o=Wd();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=gr(),n=e instanceof Error?e.message:"Render failed";throw t.recordWidgetError(i.compositionId,n),t.endWidgetLoad(i.compositionId,!1),te.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){te.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:Yi,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 te.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),te.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):te.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,te.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 Qr})),o=n();return yield o.setContent(e,t,i)}catch(e){return te.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 Qr})),n=i();return yield n.getContentSchema(t.config.compositionId)}catch(e){throw te.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 Qr})),n=i();return yield n.getDesignSchema(t.config.compositionId)}catch(e){throw te.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 Qr})),n=t();return yield n.validateContent(e,i)}catch(e){throw te.error("[EmbedSDK] Failed to validate content:",e),e}}))}getContent(e){try{return Jr().getContent(e)}catch(e){return te.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):te.warn("Overlay manager not initialized")}hideOverlay(){this.overlayManager?this.overlayManager.hideOverlay():te.warn("Overlay manager not initialized")}triggerOverlay(e,t={}){this.overlayManager?this.overlayManager.triggerOverlay(e,t):te.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 Ld=null;function Ud(e){return Ld||(Ld=new Dd(e)),Ld}"undefined"!=typeof document&&(Id(),"undefined"!=typeof MutationObserver&&new MutationObserver((()=>{Id()})).observe(document.documentElement,{childList:!0,subtree:!0}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>{hn.enabled&&te.info("DOM ready, auto-initializing SDK"),Ud().init().catch((e=>{te.error("Auto-initialization failed",{error:e})}))})):(hn.enabled&&te.info("DOM already ready, auto-initializing SDK"),setTimeout((()=>{Ud().init().catch((e=>{te.error("Auto-initialization failed",{error:e})}))}),0)));var Pd=Object.freeze({__proto__:null,EmbedSDK:Dd,getSDK:Ud});class _d{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=Or(),this.initialize()}static getInstance(){return _d.instance||(_d.instance=new _d),_d.instance}initialize(){this.initialized||(ro()?(this.loadStoredState(),this.cleanupOldEntries(),this.initialized=!0,te.info("[TextFieldManager] Initialized successfully")):te.warn("[TextFieldManager] localStorage not available, text persistence disabled"))}registerTextField(e,t,i={}){const n=this.generateStateKey(e,t);te.debug(`[TextFieldManager] Registering text field: ${e}.${t}`,{config:i});const o=this.textStates.get(n);return o&&i.autoRestore&&this.shouldAutoRestore(o,i)&&te.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 te.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&&(te.warn(`[TextFieldManager] Text exceeds maxLength (${n.maxLength}), truncating`),d=r.substring(0,n.maxLength));const l={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,l),n.autoPersist&&n.persistState&&this.debouncePersist(a,n.debounceDelay||1e3),te.debug(`[TextFieldManager] Updated text field: ${a}`,{textLength:d.length,textType:l.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(),te.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(),te.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 te.info("[TextFieldManager] Storage version mismatch, clearing stored data"),void localStorage.removeItem(this.storageKey);t.textStates&&(this.textStates=new Map(Object.entries(t.textStates)),te.debug(`[TextFieldManager] Loaded ${this.textStates.size} text field states from storage`)),"boolean"==typeof t.autoRestoreEnabled&&(this.autoRestoreEnabled=t.autoRestoreEnabled)}catch(e){te.warn("[TextFieldManager] Failed to load stored state:",e),localStorage.removeItem(this.storageKey)}}persistState(){if(ro())try{const e={version:this.storageVersion,textStates:Object.fromEntries(this.textStates),timestamp:Date.now(),autoRestoreEnabled:this.autoRestoreEnabled};localStorage.setItem(this.storageKey,JSON.stringify(e)),te.debug(`[TextFieldManager] Persisted state for ${this.textStates.size} text fields`)}catch(e){te.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(),te.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(),te.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(),ro()&&localStorage.removeItem(this.storageKey),te.debug("[TextFieldManager] Cleaned up all data")}configureSecurity(e){this.securityManager.updateConfig(e),te.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),te.info(`[TextFieldManager] Unblocked instance: ${e}`)}getSecurityStats(){return this.securityManager.getSecurityStats()}validateText(e,t,i,n){return this.securityManager.validateTextFieldUpdate(e,t,i,n)}}function zd(){return _d.getInstance()}var qd=Object.freeze({__proto__:null,TextFieldManager:_d,getTextField:function(e,t){return zd().getTextField(e,t)},getTextFieldManager:zd,registerTextField:function(e,t,i){return zd().registerTextField(e,t,i)},updateTextField:function(e,t,i,n,o){zd().updateTextField(e,t,i,n,o)}});e.BootstrapManager=bn,e.FastWidgetScanner=yn,e.ProgressiveChunkLoader=wn,e.getBootstrapStats=Tn,e.initializeWidgeticFast=kn}));
|