@widgetic/embed-sdk 2.0.14 → 2.0.16

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.
Files changed (37) hide show
  1. package/README.md +18 -0
  2. package/dist/browser/chunks/ABTestManager.js +1 -1
  3. package/dist/browser/chunks/advanced.js +1 -1
  4. package/dist/browser/chunks/api.js +1 -1
  5. package/dist/browser/chunks/core.js +1 -1
  6. package/dist/browser/chunks/display.js +1 -1
  7. package/dist/browser/chunks/media.js +1 -1
  8. package/dist/browser/chunks/messaging.js +1 -1
  9. package/dist/browser/chunks/renderers.js +1 -1
  10. package/dist/browser/chunks/scanner.js +1 -1
  11. package/dist/browser/chunks/security.js +1 -1
  12. package/dist/browser/embed-bootstrap.js +1 -1
  13. package/dist/browser/embed-sdk.js +1 -1
  14. package/dist/esm/chunks/ABTestManager.js +1 -1
  15. package/dist/esm/chunks/advanced.js +1 -1
  16. package/dist/esm/chunks/api.js +1 -1
  17. package/dist/esm/chunks/core.js +1 -1
  18. package/dist/esm/chunks/display.js +1 -1
  19. package/dist/esm/chunks/media.js +1 -1
  20. package/dist/esm/chunks/messaging.js +1 -1
  21. package/dist/esm/chunks/renderers.js +1 -1
  22. package/dist/esm/chunks/scanner.js +1 -1
  23. package/dist/esm/chunks/security.js +1 -1
  24. package/dist/esm/embed-bootstrap.js +1 -1
  25. package/dist/esm/embed-sdk.js +1 -1
  26. package/dist/esm/types/abTesting/ABTestElement.d.ts +10 -0
  27. package/dist/esm/types/abTesting/ABTestManager.d.ts +54 -12
  28. package/dist/esm/types/abTesting/abVisitor.d.ts +31 -0
  29. package/dist/esm/types/utils/declarative-embed-parser.d.ts +14 -0
  30. package/dist/esm/types/utils/image-delivery.d.ts +54 -0
  31. package/dist/esm/types/utils/lookup-cache.d.ts +34 -0
  32. package/dist/esm/types/utils/preload-content-images.d.ts +21 -0
  33. package/dist/esm/types/utils/public-embed-lookup.d.ts +3 -0
  34. package/dist/esm/types/utils/published-host-bridge.d.ts +16 -0
  35. package/dist/umd/embed-bootstrap.js +1 -1
  36. package/dist/umd/embed-sdk.js +1 -1
  37. package/package.json +1 -1
@@ -1 +1 @@
1
- import{m as t}from"./core.js";import{M as e,f as i,h as r,i as n}from"./api.js";function a(e){const i=e.getAttribute("composition-id");if(!i)throw new Error("Missing required composition-id attribute");return{compositionId:i,renderMode:o(e.getAttribute("render-mode")),displayMode:s(e.getAttribute("display-mode")),resize:u(e.getAttribute("resize")),width:parseInt(e.getAttribute("width")||"")||t.width,height:parseInt(e.getAttribute("height")||"")||t.height,autoscale:S(e),adaptive:c(e.getAttribute("adaptive")),responsive:l(e.getAttribute("responsive")),device:L(e),fullscreen:d(e),triggers:j(e),overlay:g(e),popup:w(e),media:z(e),content:I(e)}}function o(t){switch(t){case"iframe":case"custom-element":return t;default:return"auto"}}function s(t){switch(t){case"overlay":case"popup":case"fullscreen":case"modal":return t;default:return"inline"}}function u(t){switch(t){case"fill-width":case"fill-height":case"fixed":case"fixed-height":case"fixed-width":case"allow-scale-down":case"fill":return t;default:return"fixed"}}function c(t){if(!t)return;const e=parseInt(t);return isNaN(e)?void 0:e}function l(t){if(!t)return;const e=parseInt(t);return isNaN(e)?void 0:e}function d(t){if("enabled"===t.getAttribute("fullscreen")||"true"===t.getAttribute("fullscreen-enabled"))return{enabled:!0,trigger:p(t.getAttribute("fullscreen-trigger")),showControls:"false"!==t.getAttribute("fullscreen-controls"),exitOnEscape:"false"!==t.getAttribute("fullscreen-exit-on-escape"),allowAutoEnter:"true"===t.getAttribute("fullscreen-auto-enter")}}function p(t){switch(t){case"click":case"double-click":case"hover":case"auto":case"manual":return t;default:return"click"}}function g(t){if("enabled"===t.getAttribute("overlay")||"true"===t.getAttribute("overlay-enabled"))return{enabled:!0,position:y(t.getAttribute("overlay-position")),backdrop:m(t),background:f(t,m(t)),closeOnBackdropClick:"false"!==t.getAttribute("overlay-close-on-backdrop"),closeOnEscape:"false"!==t.getAttribute("overlay-close-on-escape"),showCloseButton:"false"!==t.getAttribute("overlay-close-button"),trigger:h(t.getAttribute("overlay-trigger")),width:t.getAttribute("overlay-width")||void 0,height:t.getAttribute("overlay-height")||void 0,maxWidth:t.getAttribute("overlay-max-width")||void 0,maxHeight:t.getAttribute("overlay-max-height")||void 0,zIndex:parseInt(t.getAttribute("overlay-z-index")||"")||void 0,animation:v(t.getAttribute("overlay-animation")),overlayWidth:t.getAttribute("overlay-width")||void 0,overlayHeight:t.getAttribute("overlay-height")||void 0,overlayResize:A(t.getAttribute("overlay-resize-mode")),keepDimensions:"false"!==t.getAttribute("keep-dimensions"),embedTarget:t.getAttribute("embed-target")||void 0}}function b(t){return"true"===t.getAttribute("overlay-backdrop")}function m(t){return"false"!==t.getAttribute("overlay-backdrop")}function f(t,e){if(!e)return;const i=t.getAttribute("overlay-background-color")||void 0,r=t.getAttribute("overlay-background-opacity"),n=null===r?Number.NaN:Number(r);return{enabled:!0,color:i,opacity:Number.isFinite(n)?n:void 0}}function h(t){switch(t){case"click":case"hover":case"manual":case"auto":return t;default:return"click"}}function v(t){switch(t){case"fade":case"slide-up":case"slide-down":case"slide-left":case"slide-right":case"zoom":case"bounce":case"none":return t;case"scale":return"zoom";case"slide":return"slide-up";default:return"fade"}}function y(t){switch(t){case"top":case"bottom":case"left":case"right":case"top-left":case"top-right":case"bottom-left":case"bottom-right":return t;case"top-center":return"top";case"center-left":return"left";case"center-right":return"right";case"bottom-center":return"bottom";default:return"center"}}function A(t){switch(t){case"fillWidth":return"fill-width";case"fillHeight":return"fill-height";case"fixedSize":return"fixed";case"fixedHeight":return"fixed-height";case"fixedWidth":return"fixed-width";case"allowScaleDown":return"allow-scale-down";case"fill":return"fill";default:return}}function w(t){if("enabled"===t.getAttribute("popup")||"true"===t.getAttribute("popup-enabled"))return{enabled:!0,trigger:k(t.getAttribute("popup-trigger")),width:parseInt(t.getAttribute("popup-width")||"")||void 0,height:parseInt(t.getAttribute("popup-height")||"")||void 0,centerScreen:"false"!==t.getAttribute("popup-center"),allowResize:"true"===t.getAttribute("popup-resizable"),showToolbar:"true"===t.getAttribute("popup-toolbar"),target:t.getAttribute("popup-target")||void 0}}function k(t){switch(t){case"click":case"manual":return t;default:return"click"}}function S(t){const e=t.getAttribute("autoscale");return!!e&&(("true"===e||""===e||"false"!==e)&&(C(t)||!0))}function C(t){return t.getAttribute("autoscale-min-height")||t.getAttribute("autoscale-max-height")||t.getAttribute("autoscale-debounce")||t.getAttribute("autoscale-threshold")||t.getAttribute("autoscale-animate")||t.getAttribute("autoscale-animation-duration")?{enabled:!0,minHeight:parseInt(t.getAttribute("autoscale-min-height")||"")||void 0,maxHeight:parseInt(t.getAttribute("autoscale-max-height")||"")||void 0,debounceDelay:parseInt(t.getAttribute("autoscale-debounce")||"")||void 0,threshold:parseInt(t.getAttribute("autoscale-threshold")||"")||void 0,animate:"false"!==t.getAttribute("autoscale-animate"),animationDuration:parseInt(t.getAttribute("autoscale-animation-duration")||"")||void 0}:null}function O(t){return`${t}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function x(t){return"widgetic"===t.tagName.toLowerCase()&&t.hasAttribute("composition-id")}function z(t){const e={},i=t.getAttribute("media-auto-pause")||t.getAttribute("data-media-auto-pause");null!==i&&(e.autoPause="true"===i||""===i);const r=t.getAttribute("media-type")||t.getAttribute("data-media-type");r&&["audio","video","both"].includes(r)&&(e.mediaType=r);const n=t.getAttribute("media-priority")||t.getAttribute("data-media-priority");if(n){const t=parseInt(n,10);!isNaN(t)&&t>=0&&t<=10&&(e.priority=t)}const a=t.getAttribute("media-persist-state")||t.getAttribute("data-media-persist-state");null!==a&&(e.persistState="true"===a||""===a);const o=t.getAttribute("media-allow-simultaneous")||t.getAttribute("data-media-allow-simultaneous");if(o){const t=o.split(",").map((t=>t.trim())).filter((t=>["audio","video"].includes(t)));t.length>0&&(e.allowSimultaneous=t)}const s=t.getAttribute("media-auto-resume")||t.getAttribute("data-media-auto-resume");null!==s&&(e.autoResume="true"===s||""===s);const u=t.getAttribute("media-auto-resume-timeout")||t.getAttribute("data-media-auto-resume-timeout");if(u){const t=parseInt(u,10);!isNaN(t)&&t>0&&(e.autoResumeTimeout=t)}const c=t.getAttribute("media-global-volume")||t.getAttribute("data-media-global-volume");return null!==c&&(e.globalVolume="true"===c||""===c),e}function I(t){const e={},i=t.getAttribute("content-type")||t.getAttribute("data-content-type");i&&["gallery","carousel","slider","stepper","tabs","list","custom"].includes(i)&&(e.contentType=i);const r=t.getAttribute("content-persist-state")||t.getAttribute("data-content-persist-state");null!==r&&(e.persistState="true"===r||""===r);const n=t.getAttribute("content-auto-resume")||t.getAttribute("data-content-auto-resume");null!==n&&(e.autoResume="true"===n||""===n);const a=t.getAttribute("content-auto-resume-timeout")||t.getAttribute("data-content-auto-resume-timeout");if(a){const t=parseInt(a,10);!isNaN(t)&&t>0&&(e.autoResumeTimeout=t)}const o=t.getAttribute("content-track-metadata")||t.getAttribute("data-content-track-metadata");return null!==o&&(e.trackMetadata="true"===o||""===o),Object.keys(e).length>0?e:void 0}function j(t){const e=t.getAttribute("embed-target");if("overlay"!==e&&"mixed"!==e)return;const i=function(t){switch(t){case"page-load":return"pageLoad";case"exit-intent":return"exitIntent";case"delay":return"delay";case"scroll":return"scroll";default:return}}(t.getAttribute("event-trigger")),r=parseInt(t.getAttribute("max-views")||""),n=parseInt(t.getAttribute("time-period")||""),a=Number.isFinite(r)&&r>0||Number.isFinite(n)&&n>0;return Object.assign(Object.assign(Object.assign({mode:e,eventTrigger:i},"overlay"===e&&"delay"===i?{delay:{enabled:!0,delayMs:N(t)}}:{}),"overlay"===e&&"scroll"===i?{scroll:{enabled:!0,threshold:.1,distance:T(t),direction:"down"}}:{}),{overlay:{position:t.getAttribute("overlay-position")||void 0,keepDimensions:"false"!==t.getAttribute("keep-dimensions"),zIndex:E(t),fullWidth:"true"===t.getAttribute("overlay-full-width")||void 0,overlayWidth:t.getAttribute("overlay-width")||void 0,overlayHeight:t.getAttribute("overlay-height")||void 0,overlayResize:A(t.getAttribute("overlay-resize-mode")),backdrop:b(t),background:f(t,b(t)),closeButton:!0},recurrence:a?{enabled:!0,maxViews:Number.isFinite(r)&&r>0?r:Number.MAX_SAFE_INTEGER,timePeriodHours:Number.isFinite(n)&&n>0?n:24}:void 0})}function E(t){const i=parseInt(t.getAttribute("overlay-z-index")||"");if(Number.isFinite(i)&&!(i<=0))return Math.min(i,e)}function N(t){const e=parseInt(t.getAttribute("trigger-delay")||"");return!Number.isFinite(e)||e<0?i:Math.min(e,r)}function T(t){const e=parseInt(t.getAttribute("trigger-scroll-distance")||"");return Number.isFinite(e)&&e>0?e:n}function L(t){const e=t.getAttribute("device-mobile-enabled")||t.getAttribute("data-device-mobile-enabled"),i=t.getAttribute("device-desktop-enabled")||t.getAttribute("data-device-desktop-enabled");if(e||i)return{mobileEnabled:"false"!==e,desktopEnabled:"false"!==i}}var q=Object.freeze({__proto__:null,generateInstanceId:O,isValidWidgetElement:x,parseTriggerConfig:j,parseWidgetConfig:a});const M=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"]),R={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"},W=new WeakMap;function F(t){const e=t.trim().replace(/^data-/,"").replace(/-([a-zA-Z0-9])/g,((t,e)=>e.toUpperCase())),i=e.toLowerCase();return e===i&&R[i]?R[i]:e}function P(t){var e,i,r,n,a,o,s,u;const c=(null===(e=t.getAttribute("composition-id"))||void 0===e?void 0:e.trim())||(null===(i=t.getAttribute("compositionid"))||void 0===i?void 0:i.trim())||(null===(r=t.getAttribute("data-composition-id"))||void 0===r?void 0:r.trim())||(null===(n=t.getAttribute("composition"))||void 0===n?void 0:n.trim());if(c)return{kind:"composition",id:c};const l=(null===(a=t.getAttribute("widget"))||void 0===a?void 0:a.trim())||(null===(o=t.getAttribute("widget-id"))||void 0===o?void 0:o.trim())||(null===(s=t.getAttribute("widgetid"))||void 0===s?void 0:s.trim())||(null===(u=t.getAttribute("data-widget-id"))||void 0===u?void 0:u.trim());return l?{kind:"widget",id:l}:null}const _=new WeakSet;function H(t){if(!t||_.has(t))return;_.add(t);const e=[{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:r}of e){const e=Object.prototype.hasOwnProperty.call(t,i),n=e?t[i]:void 0;e&&delete t[i];const a=e=>{if(null==e||""===e)t.removeAttribute(r);else if("string"==typeof e)t.getAttribute(r)!==e&&t.setAttribute(r,e);else if("object"==typeof e)try{const i=JSON.stringify(e);t.getAttribute(r)!==i&&t.setAttribute(r,i)}catch(t){}};try{Object.defineProperty(t,i,{configurable:!0,enumerable:!1,get:()=>t.getAttribute(r),set(t){a(t)}}),e&&void 0!==n&&a(n)}catch(t){}}const i=[{prop:"mediaResolver",attr:"media-resolver"},{prop:"compositionId",attr:"composition-id"},{prop:"widgetId",attr:"widget-id"}];for(const{prop:e,attr:r}of i){const i=Object.prototype.hasOwnProperty.call(t,e),n=i?t[e]:void 0;i&&delete t[e];const a=e=>{if(null==e||""===e)t.removeAttribute(r);else{const i=String(e);t.getAttribute(r)!==i&&t.setAttribute(r,i)}};try{Object.defineProperty(t,e,{configurable:!0,enumerable:!1,get:()=>t.getAttribute(r),set(t){a(t)}}),i&&void 0!==n&&a(n)}catch(t){}}}function B(t){const e=P(t);return e?e.id:null}function D(t){const e=t.tagName.toUpperCase();return"IFRAME"===e||"SCRIPT"===e||"STYLE"===e||"TEMPLATE"===e||!!(t.hasAttribute("data-widgetic-direct")||t.hasAttribute("data-widgetic-internal")||t.classList.contains("widgetic-direct-target"))}function J(t){const e=t.toLowerCase();return!!M.has(e)||(!!e.startsWith("data-widgetic-")||(!!e.startsWith("aria-")||!!e.startsWith("on")))}function V(t){const e=t.trim();if("true"===e)return!0;if("false"===e)return!1;if(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))try{return JSON.parse(e)}catch(e){return t}return t}function $(t){if(!t||!t.trim())return null;try{const e=JSON.parse(t);if(e&&"object"==typeof e&&!Array.isArray(e))return e}catch(t){}return null}function G(t){if(!t||!t.trim())return null;try{const e=JSON.parse(t);if(Array.isArray(e))return e.filter((t=>Boolean(t&&"object"==typeof t&&!Array.isArray(t)))).map(((t,e)=>Object.assign(Object.assign({id:"string"==typeof t.id&&t.id.trim()?t.id:`item-${e+1}`,order:e+1},t),{metadata:Object.assign({service:"declarative"},t)})))}catch(t){}return null}function U(t){var e;const i=Array.from(t.children).filter((t=>!D(t)));if(0===i.length)return null!==(e=W.get(t))&&void 0!==e?e:[];const r=i.map(((t,e)=>{var i;t.hasAttribute("data-widgetic-item")||(t.setAttribute("data-widgetic-item","1"),t instanceof HTMLElement&&(t.hidden=!0,t.style.display="none"));const r={};for(const e of Array.from(t.attributes)){const t=e.name.toLowerCase();if("data-widgetic-item"===t||"hidden"===t)continue;if("style"===t&&"display:none;"===e.value.replace(/\s+/g,""))continue;const i=F(e.name);i&&!(i in Object.prototype)&&(r[i]=V(e.value))}if(0===t.children.length){const e=null===(i=t.textContent)||void 0===i?void 0:i.trim();e&&(void 0===r.content&&(r.content=e),void 0===r.text&&(r.text=e))}const n="string"==typeof r.id&&r.id.trim()?r.id:`item-${e+1}`;return Object.assign(Object.assign({id:n,order:e+1},r),{metadata:Object.assign({service:"declarative"},r)})}));return W.set(t,r),r}function X(t,e){if(!t)return null;if(e in t)return e;const i=e.toLowerCase();for(const e of Object.keys(t))if(e.toLowerCase()===i)return e;return null}function Y(t,e){const i={},r={},n=$(t.getAttribute("design"));if(n)for(const[t,e]of Object.entries(n))t in Object.prototype||null==e||(i[t]="string"==typeof e?e:JSON.stringify(e));const a=$(t.getAttribute("content"));if(a)for(const[t,e]of Object.entries(a))t in Object.prototype||void 0===e||(r[t]=e);const o=$(t.getAttribute("values"));if(o)for(const[t,e]of Object.entries(o))t in Object.prototype||void 0===e||(r[t]=e);for(const n of Array.from(t.attributes)){const t=n.name,a=t.toLowerCase();if(a.startsWith("design-")&&a.length>7){const r=F(t.slice(7));if(r&&!(r in Object.prototype)){i[X(null==e?void 0:e.design,r)||r]=n.value}continue}if(a.startsWith("content-")&&"content-items"!==a&&a.length>8){const i=F(t.slice(8));if(i&&!(i in Object.prototype)){r[X(null==e?void 0:e.content,i)||i]=V(n.value)}continue}if(J(t))continue;const o=F(t);if(!o||o in Object.prototype)continue;const s=X(null==e?void 0:e.content,o),u=X(null==e?void 0:e.design,o);if(s&&!u)r[s]=V(n.value);else if(u&&!s)i[u]=n.value;else{i[o]=n.value,r[o]=V(n.value);const e=t.replace(/^data-/,"");e===o||e in Object.prototype||(i[e]=n.value)}}let s=U(t);if(0===s.length){const e=G(t.getAttribute("content-items"))||G(t.getAttribute("contentitems"))||G(t.getAttribute("items"));e&&e.length>0&&(s=e)}return{design:i,content:r,contentItems:s,hasOverrides:Object.keys(i).length>0||Object.keys(r).length>0||s.length>0}}function Z(t,e){const i=null!=e?e:{},r=Y(t,i);return r.hasOverrides?Object.assign(Object.assign({},i),{design:Object.assign(Object.assign({},i.design||{}),r.design),content:Object.assign(Object.assign({},i.content||{}),r.content),contentItems:r.contentItems.length>0?r.contentItems:i.contentItems||[]}):i}function K(t){var e,i;if(0===t.length)return!0;for(const r of t){if("attributes"===r.type){const t=(null===(e=r.attributeName)||void 0===e?void 0:e.toLowerCase())||"";if(!t)continue;if("data-widgetic-mounted"===t||"data-widgetic-mounting"===t||"data-widgetic-refused"===t||"data-widgetic-context-invalid"===t||"data-widgetic-overlay"===t||"data-device-restricted"===t||"data-widgetic-item"===t||"hidden"===t)continue;if("style"===t&&r.target!==(null===(i=r.target.ownerDocument)||void 0===i?void 0:i.body)&&r.target instanceof Element&&r.target.hasAttribute("data-widgetic-item"))continue;if(r.target instanceof Element&&D(r.target))continue;return!0}if("childList"===r.type){if([...Array.from(r.addedNodes),...Array.from(r.removedNodes)].some((t=>!(t instanceof Element&&D(t)))))return!0}if("characterData"===r.type){const t=r.target.parentElement;if(t&&!D(t))return!0}}return!1}const Q=new WeakMap;function tt(t,e,i){const r=Q.get(t);r&&r();const n="undefined"!=typeof MutationObserver?MutationObserver:null;if(!n)return()=>{};let a,o=!1;try{a=new n((r=>{K(r)&&(o||(o=!0,queueMicrotask((()=>{o=!1;const r=Y(t,e);i(r)}))))}))}catch(t){return()=>{}}a.observe(t,{attributes:!0,childList:!0,subtree:!0,characterData:!0});const s=()=>{a.disconnect(),Q.delete(t)};return Q.set(t,s),s}function et(t){const e=Q.get(t);e&&e()}function it(){return"undefined"==typeof window?{customElements:!1,http3:!1,resizeObserver:!1,fullscreenApi:!1,popupBlocking:!1}:{customElements:"undefined"!=typeof customElements&&"function"==typeof customElements.define,http3:rt(),resizeObserver:"undefined"!=typeof ResizeObserver,fullscreenApi:nt(),popupBlocking:at()}}function rt(){if("undefined"==typeof performance||!performance.getEntriesByType)return!1;try{const t=performance.getEntriesByType("navigation");if(t.length>0){const e=t[0];return"h3"===e.nextHopProtocol||"h3-29"===e.nextHopProtocol}return!1}catch(t){return!1}}function nt(){return!("undefined"==typeof document||!document.documentElement)&&!!(document.documentElement.requestFullscreen||document.documentElement.webkitRequestFullscreen||document.documentElement.mozRequestFullScreen||document.documentElement.msRequestFullscreen)}function at(){if("undefined"==typeof window||!window.open)return!1;try{const t=window.open("","widgetic-popup-test","width=1,height=1");return!t||(t.close(),!1)}catch(t){return!0}}function ot(t,e){switch(t){case"custom-element":case"auto":default:return e.customElements?"custom-element":"iframe";case"iframe":return"iframe"}}function st(){if("undefined"==typeof localStorage)return!1;try{const t="widgetic-test";return localStorage.setItem(t,t),localStorage.removeItem(t),!0}catch(t){return!1}}var ut=Object.freeze({__proto__:null,checkSdkInitialization:function(){if("undefined"==typeof window)return!1;const t="widgetic-sdk-initialized";return st()?!!localStorage.getItem(t)||(localStorage.setItem(t,Date.now().toString()),!1):!!window.__widgeticInitialized},clearSdkInitialization:function(){st()&&localStorage.removeItem("widgetic-sdk-initialized"),delete window.__widgeticInitialized},detectBrowserCapabilities:it,determineBestRenderMode:ot,hasIntersectionObserver:function(){return"undefined"!=typeof IntersectionObserver},isLocalStorageAvailable:st});class ct{static analyzeElement(t){try{const e=this.getExplicitMetadata(t);return e||this.analyzeHeuristically(t)}catch(t){return null}}static getExplicitMetadata(t){const e=t.getAttribute("data-widget-meta");if(e)try{return JSON.parse(e)}catch(t){}const i=t.getAttribute("data-capabilities");if(i)return this.parseCapabilitiesString(i);const r=t.querySelector('script[type="application/json"]');if(r&&r.textContent)try{const t=JSON.parse(r.textContent);return t.capabilities||t.metadata}catch(t){}return null}static analyzeHeuristically(t){const e={type:"custom",version:"1.0.0"},i=t.getAttribute("data-widget-type")||t.getAttribute("data-type")||this.inferTypeFromStructure(t);switch(i&&(e.type=i),e.type){case"media":e.mediaCapabilities=this.analyzeMediaCapabilities(t);break;case"gallery":e.contentCapabilities=this.analyzeContentCapabilities(t);break;case"form":e.textCapabilities=this.analyzeTextCapabilities(t);break;case"interactive":e.interactionCapabilities=this.analyzeInteractionCapabilities(t)}return e.supportsResponsive=this.checkResponsiveSupport(t),e.supportsAutoscale=this.checkAutoscaleSupport(t),e.supportsThemes=this.checkThemeSupport(t),e.displayCapabilities=this.analyzeDisplayCapabilities(t),e.abTestingCapabilities=this.analyzeABTestingCapabilities(t),e}static inferTypeFromStructure(t){var e;return t.querySelector("video, audio")||t.classList.contains("media-widget")||(null===(e=t.getAttribute("data-widget-id"))||void 0===e?void 0:e.includes("video"))?"media":t.querySelector("form, input, textarea")||t.classList.contains("form-widget")?"form":t.querySelector(".gallery, .carousel")||t.classList.contains("gallery-widget")||t.querySelectorAll("img").length>1?"gallery":t.querySelector("button, .interactive")||t.classList.contains("quiz-widget")||t.classList.contains("poll-widget")?"interactive":"custom"}static analyzeMediaCapabilities(t){const e=t.querySelectorAll("video"),i=t.querySelectorAll("audio"),r=null!==t.querySelector("[controls]"),n=null!==t.querySelector("[data-volume], .volume-control");let a="audio";return e.length>0&&i.length>0?a="mixed":e.length>0&&(a="video"),{supportsPlay:!0,supportsPause:!0,supportsVolumeControl:n||r,supportsSeek:r,supportsGlobalVolume:t.hasAttribute("data-global-volume"),mediaType:a}}static analyzeContentCapabilities(t){const e=t.querySelectorAll(".item, .slide, img, .content-item"),i=null!==t.querySelector(".nav, .navigation, button"),r=t.hasAttribute("data-position")||t.hasAttribute("data-track-position");let n="gallery";return t.classList.contains("carousel")&&(n="carousel"),t.classList.contains("list")&&(n="list"),t.classList.contains("grid")&&(n="grid"),{supportsPositionTracking:r,supportsNavigation:i,contentType:n,totalItems:e.length}}static analyzeTextCapabilities(t){const e=t.querySelectorAll("input, textarea, select"),i=Array.from(e).map((t=>t.getAttribute("name")||t.getAttribute("id")||"unknown"));return{supportsTextPersistence:t.hasAttribute("data-persist")||t.hasAttribute("data-autosave"),supportsSanitization:!0,fields:i}}static analyzeInteractionCapabilities(t){const e=t.querySelectorAll("button").length>0,i=t.querySelectorAll("form").length>0,r=t.hasAttribute("data-events")||t.hasAttribute("data-track-interactions"),n=[],a=t.getAttribute("data-events");return a&&n.push(...a.split(",").map((t=>t.trim()))),{supportsClicks:e||null!==t.querySelector("[onclick]"),supportsFormSubmission:i,supportsCustomEvents:r,customEventTypes:n.length>0?n:void 0}}static analyzeDisplayCapabilities(t){return{supportsFullscreen:t.hasAttribute("data-fullscreen")||t.classList.contains("fullscreen-capable"),supportsOverlay:t.hasAttribute("data-overlay")||t.classList.contains("overlay-capable"),supportsPopup:t.hasAttribute("data-popup")||t.classList.contains("popup-capable"),supportsInline:!0}}static analyzeABTestingCapabilities(t){if(!("widgetic-abtest"===t.tagName.toLowerCase()||t.hasAttribute("experiment-id")||t.hasAttribute("data-ab-test")))return;const e=[],i=[];return t.querySelector("button, a, [onclick]")&&(e.push("clicks"),i.push("clicks")),t.querySelector("form")&&(e.push("submissions"),i.push("conversions")),t.querySelector("video, audio")&&(e.push("plays"),i.push("plays")),e.push("impressions"),{supportsTracking:!0,trackableEvents:e,conversionGoals:i}}static checkResponsiveSupport(t){return t.hasAttribute("data-responsive")||t.hasAttribute("data-breakpoints")||t.classList.contains("responsive")}static checkAutoscaleSupport(t){return t.hasAttribute("data-autoscale")||t.hasAttribute("data-auto-height")||t.classList.contains("autoscale")}static checkThemeSupport(t){return t.hasAttribute("data-theme")||t.classList.contains("themeable")||null!==t.querySelector("[data-theme]")}static parseCapabilitiesString(t){const e=t.split(",").map((t=>t.trim()));return{type:"custom",version:"1.0.0",mediaCapabilities:e.includes("media")?{supportsPlay:!0,supportsPause:!0,supportsVolumeControl:e.includes("volume"),supportsSeek:e.includes("seek"),supportsGlobalVolume:e.includes("global-volume"),mediaType:"mixed"}:void 0,textCapabilities:e.includes("forms")?{supportsTextPersistence:e.includes("persist"),supportsSanitization:!0,fields:[]}:void 0,interactionCapabilities:e.includes("interactive")?{supportsClicks:!0,supportsFormSubmission:e.includes("forms"),supportsCustomEvents:e.includes("events")}:void 0,supportsResponsive:e.includes("responsive"),supportsAutoscale:e.includes("autoscale"),supportsThemes:e.includes("themes")}}}function lt(t){var e,i,r,n;const a=new Set;return a.add("rendering"),a.add("api"),t.mediaCapabilities&&a.add("media"),t.textCapabilities&&a.add("security"),t.interactionCapabilities&&a.add("messaging"),((null===(e=t.displayCapabilities)||void 0===e?void 0:e.supportsFullscreen)||(null===(i=t.displayCapabilities)||void 0===i?void 0:i.supportsOverlay)||(null===(r=t.displayCapabilities)||void 0===r?void 0:r.supportsPopup))&&a.add("display"),t.abTestingCapabilities&&(a.add("abTesting"),a.add("messaging")),(null===(n=t.performanceRequirements)||void 0===n?void 0:n.requiresLazyLoading)&&a.add("performance"),Array.from(a)}var dt=Object.freeze({__proto__:null,WidgetMetadataAnalyzer:ct,analyzeWidgetRequirementsEnhanced:function(t){const e=new Set;for(const i of t){const t=ct.analyzeElement(i);if(t){lt(t).forEach((t=>e.add(t)))}}return Array.from(e)},getRequiredChunks:lt});export{Y as a,P as b,U as c,it as d,x as e,ot as f,B as g,K as h,H as i,O as j,st as k,q as l,Z as m,ut as n,tt as o,a as p,et as s,dt as w};
1
+ import{D as t}from"./core.js";const e=3e3,i=99999999,r=2147483647;function n(e){const i=e.getAttribute("composition-id");if(!i)throw new Error("Missing required composition-id attribute");return{compositionId:i,renderMode:o(e.getAttribute("render-mode")),displayMode:a(e.getAttribute("display-mode")),resize:s(e.getAttribute("resize")),width:parseInt(e.getAttribute("width")||"")||t.width,height:parseInt(e.getAttribute("height")||"")||t.height,autoscale:S(e),adaptive:c(e.getAttribute("adaptive")),responsive:u(e.getAttribute("responsive")),device:T(e),fullscreen:l(e),triggers:x(e),overlay:p(e),popup:A(e),media:j(e),content:I(e)}}function o(t){switch(t){case"iframe":case"custom-element":return t;default:return"auto"}}function a(t){switch(t){case"overlay":case"popup":case"fullscreen":case"modal":return t;default:return"inline"}}function s(t){switch(t){case"fill-width":case"fill-height":case"fixed":case"fixed-height":case"fixed-width":case"allow-scale-down":case"fill":return t;default:return"fixed"}}function c(t){if(!t)return;const e=parseInt(t);return isNaN(e)?void 0:e}function u(t){if(!t)return;const e=parseInt(t);return isNaN(e)?void 0:e}function l(t){if("enabled"===t.getAttribute("fullscreen")||"true"===t.getAttribute("fullscreen-enabled"))return{enabled:!0,trigger:d(t.getAttribute("fullscreen-trigger")),showControls:"false"!==t.getAttribute("fullscreen-controls"),exitOnEscape:"false"!==t.getAttribute("fullscreen-exit-on-escape"),allowAutoEnter:"true"===t.getAttribute("fullscreen-auto-enter")}}function d(t){switch(t){case"click":case"double-click":case"hover":case"auto":case"manual":return t;default:return"click"}}function p(t){if("enabled"===t.getAttribute("overlay")||"true"===t.getAttribute("overlay-enabled"))return{enabled:!0,position:h(t.getAttribute("overlay-position")),backdrop:b(t),background:f(t,b(t)),closeOnBackdropClick:"false"!==t.getAttribute("overlay-close-on-backdrop"),closeOnEscape:"false"!==t.getAttribute("overlay-close-on-escape"),showCloseButton:"false"!==t.getAttribute("overlay-close-button"),trigger:m(t.getAttribute("overlay-trigger")),width:t.getAttribute("overlay-width")||void 0,height:t.getAttribute("overlay-height")||void 0,maxWidth:t.getAttribute("overlay-max-width")||void 0,maxHeight:t.getAttribute("overlay-max-height")||void 0,zIndex:parseInt(t.getAttribute("overlay-z-index")||"")||void 0,animation:y(t.getAttribute("overlay-animation")),overlayWidth:t.getAttribute("overlay-width")||void 0,overlayHeight:t.getAttribute("overlay-height")||void 0,overlayResize:v(t.getAttribute("overlay-resize-mode")),keepDimensions:"false"!==t.getAttribute("keep-dimensions"),embedTarget:t.getAttribute("embed-target")||void 0}}function g(t){return"true"===t.getAttribute("overlay-backdrop")}function b(t){return"false"!==t.getAttribute("overlay-backdrop")}function f(t,e){if(!e)return;const i=t.getAttribute("overlay-background-color")||void 0,r=t.getAttribute("overlay-background-opacity"),n=null===r?Number.NaN:Number(r);return{enabled:!0,color:i,opacity:Number.isFinite(n)?n:void 0}}function m(t){switch(t){case"click":case"hover":case"manual":case"auto":return t;default:return"click"}}function y(t){switch(t){case"fade":case"slide-up":case"slide-down":case"slide-left":case"slide-right":case"zoom":case"bounce":case"none":return t;case"scale":return"zoom";case"slide":return"slide-up";default:return"fade"}}function h(t){switch(t){case"top":case"bottom":case"left":case"right":case"top-left":case"top-right":case"bottom-left":case"bottom-right":return t;case"top-center":return"top";case"center-left":return"left";case"center-right":return"right";case"bottom-center":return"bottom";default:return"center"}}function v(t){switch(t){case"fillWidth":return"fill-width";case"fillHeight":return"fill-height";case"fixedSize":return"fixed";case"fixedHeight":return"fixed-height";case"fixedWidth":return"fixed-width";case"allowScaleDown":return"allow-scale-down";case"fill":return"fill";default:return}}function A(t){if("enabled"===t.getAttribute("popup")||"true"===t.getAttribute("popup-enabled"))return{enabled:!0,trigger:w(t.getAttribute("popup-trigger")),width:parseInt(t.getAttribute("popup-width")||"")||void 0,height:parseInt(t.getAttribute("popup-height")||"")||void 0,centerScreen:"false"!==t.getAttribute("popup-center"),allowResize:"true"===t.getAttribute("popup-resizable"),showToolbar:"true"===t.getAttribute("popup-toolbar"),target:t.getAttribute("popup-target")||void 0}}function w(t){switch(t){case"click":case"manual":return t;default:return"click"}}function S(t){const e=t.getAttribute("autoscale");return!!e&&(("true"===e||""===e||"false"!==e)&&(k(t)||!0))}function k(t){return t.getAttribute("autoscale-min-height")||t.getAttribute("autoscale-max-height")||t.getAttribute("autoscale-debounce")||t.getAttribute("autoscale-threshold")||t.getAttribute("autoscale-animate")||t.getAttribute("autoscale-animation-duration")?{enabled:!0,minHeight:parseInt(t.getAttribute("autoscale-min-height")||"")||void 0,maxHeight:parseInt(t.getAttribute("autoscale-max-height")||"")||void 0,debounceDelay:parseInt(t.getAttribute("autoscale-debounce")||"")||void 0,threshold:parseInt(t.getAttribute("autoscale-threshold")||"")||void 0,animate:"false"!==t.getAttribute("autoscale-animate"),animationDuration:parseInt(t.getAttribute("autoscale-animation-duration")||"")||void 0}:null}function C(t){return`${t}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function O(t){return"widgetic"===t.tagName.toLowerCase()&&t.hasAttribute("composition-id")}function j(t){const e={},i=t.getAttribute("media-auto-pause")||t.getAttribute("data-media-auto-pause");null!==i&&(e.autoPause="true"===i||""===i);const r=t.getAttribute("media-type")||t.getAttribute("data-media-type");r&&["audio","video","both"].includes(r)&&(e.mediaType=r);const n=t.getAttribute("media-priority")||t.getAttribute("data-media-priority");if(n){const t=parseInt(n,10);!isNaN(t)&&t>=0&&t<=10&&(e.priority=t)}const o=t.getAttribute("media-persist-state")||t.getAttribute("data-media-persist-state");null!==o&&(e.persistState="true"===o||""===o);const a=t.getAttribute("media-allow-simultaneous")||t.getAttribute("data-media-allow-simultaneous");if(a){const t=a.split(",").map((t=>t.trim())).filter((t=>["audio","video"].includes(t)));t.length>0&&(e.allowSimultaneous=t)}const s=t.getAttribute("media-auto-resume")||t.getAttribute("data-media-auto-resume");null!==s&&(e.autoResume="true"===s||""===s);const c=t.getAttribute("media-auto-resume-timeout")||t.getAttribute("data-media-auto-resume-timeout");if(c){const t=parseInt(c,10);!isNaN(t)&&t>0&&(e.autoResumeTimeout=t)}const u=t.getAttribute("media-global-volume")||t.getAttribute("data-media-global-volume");return null!==u&&(e.globalVolume="true"===u||""===u),e}function I(t){const e={},i=t.getAttribute("content-type")||t.getAttribute("data-content-type");i&&["gallery","carousel","slider","stepper","tabs","list","custom"].includes(i)&&(e.contentType=i);const r=t.getAttribute("content-persist-state")||t.getAttribute("data-content-persist-state");null!==r&&(e.persistState="true"===r||""===r);const n=t.getAttribute("content-auto-resume")||t.getAttribute("data-content-auto-resume");null!==n&&(e.autoResume="true"===n||""===n);const o=t.getAttribute("content-auto-resume-timeout")||t.getAttribute("data-content-auto-resume-timeout");if(o){const t=parseInt(o,10);!isNaN(t)&&t>0&&(e.autoResumeTimeout=t)}const a=t.getAttribute("content-track-metadata")||t.getAttribute("data-content-track-metadata");return null!==a&&(e.trackMetadata="true"===a||""===a),Object.keys(e).length>0?e:void 0}function x(t){const e=t.getAttribute("embed-target");if("overlay"!==e&&"mixed"!==e)return;const i=function(t){switch(t){case"page-load":return"pageLoad";case"exit-intent":return"exitIntent";case"delay":return"delay";case"scroll":return"scroll";default:return}}(t.getAttribute("event-trigger")),r=parseInt(t.getAttribute("max-views")||""),n=parseInt(t.getAttribute("time-period")||""),o=Number.isFinite(r)&&r>0||Number.isFinite(n)&&n>0;return Object.assign(Object.assign(Object.assign({mode:e,eventTrigger:i},"overlay"===e&&"delay"===i?{delay:{enabled:!0,delayMs:E(t)}}:{}),"overlay"===e&&"scroll"===i?{scroll:{enabled:!0,threshold:.1,distance:N(t),direction:"down"}}:{}),{overlay:{position:t.getAttribute("overlay-position")||void 0,keepDimensions:"false"!==t.getAttribute("keep-dimensions"),zIndex:z(t),fullWidth:"true"===t.getAttribute("overlay-full-width")||void 0,overlayWidth:t.getAttribute("overlay-width")||void 0,overlayHeight:t.getAttribute("overlay-height")||void 0,overlayResize:v(t.getAttribute("overlay-resize-mode")),backdrop:g(t),background:f(t,g(t)),closeButton:!0},recurrence:o?{enabled:!0,maxViews:Number.isFinite(r)&&r>0?r:Number.MAX_SAFE_INTEGER,timePeriodHours:Number.isFinite(n)&&n>0?n:24}:void 0})}function z(t){const e=parseInt(t.getAttribute("overlay-z-index")||"");if(Number.isFinite(e)&&!(e<=0))return Math.min(e,r)}function E(t){const e=parseInt(t.getAttribute("trigger-delay")||"");return!Number.isFinite(e)||e<0?3e3:Math.min(e,864e5)}function N(t){const e=parseInt(t.getAttribute("trigger-scroll-distance")||"");return Number.isFinite(e)&&e>0?e:100}function T(t){const e=t.getAttribute("device-mobile-enabled")||t.getAttribute("data-device-mobile-enabled"),i=t.getAttribute("device-desktop-enabled")||t.getAttribute("data-device-desktop-enabled");if(e||i)return{mobileEnabled:"false"!==e,desktopEnabled:"false"!==i}}var L=Object.freeze({__proto__:null,generateInstanceId:C,isValidWidgetElement:O,parseTriggerConfig:x,parseWidgetConfig:n});const q=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"]),R={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"},M=new WeakMap;function W(t){const e=t.trim().replace(/^data-/,"").replace(/-([a-zA-Z0-9])/g,((t,e)=>e.toUpperCase())),i=e.toLowerCase();return e===i&&R[i]?R[i]:e}function F(t){var e,i,r,n,o,a,s,c;const u=(null===(e=t.getAttribute("composition-id"))||void 0===e?void 0:e.trim())||(null===(i=t.getAttribute("compositionid"))||void 0===i?void 0:i.trim())||(null===(r=t.getAttribute("data-composition-id"))||void 0===r?void 0:r.trim())||(null===(n=t.getAttribute("composition"))||void 0===n?void 0:n.trim());if(u)return{kind:"composition",id:u};const l=(null===(o=t.getAttribute("widget"))||void 0===o?void 0:o.trim())||(null===(a=t.getAttribute("widget-id"))||void 0===a?void 0:a.trim())||(null===(s=t.getAttribute("widgetid"))||void 0===s?void 0:s.trim())||(null===(c=t.getAttribute("data-widget-id"))||void 0===c?void 0:c.trim());return l?{kind:"widget",id:l}:null}const P=new WeakSet;function _(t){if(!t||P.has(t))return;P.add(t);const e=[{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:r}of e){const e=Object.prototype.hasOwnProperty.call(t,i),n=e?t[i]:void 0;e&&delete t[i];const o=e=>{if(null==e||""===e)t.removeAttribute(r);else if("string"==typeof e)t.getAttribute(r)!==e&&t.setAttribute(r,e);else if("object"==typeof e)try{const i=JSON.stringify(e);t.getAttribute(r)!==i&&t.setAttribute(r,i)}catch(t){}};try{Object.defineProperty(t,i,{configurable:!0,enumerable:!1,get:()=>t.getAttribute(r),set(t){o(t)}}),e&&void 0!==n&&o(n)}catch(t){}}const i=[{prop:"mediaResolver",attr:"media-resolver"},{prop:"compositionId",attr:"composition-id"},{prop:"widgetId",attr:"widget-id"}];for(const{prop:e,attr:r}of i){const i=Object.prototype.hasOwnProperty.call(t,e),n=i?t[e]:void 0;i&&delete t[e];const o=e=>{if(null==e||""===e)t.removeAttribute(r);else{const i=String(e);t.getAttribute(r)!==i&&t.setAttribute(r,i)}};try{Object.defineProperty(t,e,{configurable:!0,enumerable:!1,get:()=>t.getAttribute(r),set(t){o(t)}}),i&&void 0!==n&&o(n)}catch(t){}}}function D(t){const e=F(t);return e?e.id:null}function G(t){if("SCRIPT"!==t.tagName.toUpperCase())return!1;const e=(t.getAttribute("type")||"").trim().toLowerCase();return"application/json"===e||"application/ld+json"===e||"application/widgetic+json"===e||(t.hasAttribute("data-widgetic-json")||t.hasAttribute("data-widgetic-config"))}function H(t){const e=t.tagName.toUpperCase();return"SCRIPT"===e?!G(t):"IFRAME"===e||"STYLE"===e||"TEMPLATE"===e||!!(t.hasAttribute("data-widgetic-direct")||t.hasAttribute("data-widgetic-internal")||t.classList.contains("widgetic-direct-target"))}function B(t){const e=t.toLowerCase();return!!q.has(e)||(!!e.startsWith("data-widgetic-")||(!!e.startsWith("aria-")||!!e.startsWith("on")))}function V(t){const e=t.trim();if("true"===e)return!0;if("false"===e)return!1;if(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))try{return JSON.parse(e)}catch(e){return t}return t}function J(t){if(!t||!t.trim())return null;try{const e=JSON.parse(t);if(e&&"object"==typeof e&&!Array.isArray(e))return e}catch(t){}return null}function $(t){return t.filter((t=>Boolean(t&&"object"==typeof t&&!Array.isArray(t)))).map(((t,e)=>function(t,e){const i={};for(const[e,r]of Object.entries(t))"properties"===e||"inputController"===e||e in Object.prototype||(i[e]=r);if(Array.isArray(t.properties))for(const e of t.properties){if(!e||"object"!=typeof e||Array.isArray(e))continue;const t=e,r="string"==typeof t.name?t.name.trim():"";if(!r||r in Object.prototype)continue;const n=void 0!==t.value&&null!==t.value?t.value:t.defaultValue;void 0!==n&&(i[r]=n)}const r="string"==typeof i.id&&i.id.trim()?i.id:"string"==typeof t.id&&t.id.trim()?t.id:`item-${e+1}`;return Object.assign(Object.assign({id:r,order:e+1},i),{metadata:Object.assign({service:"declarative"},i)})}(t,e)))}function U(t){if(!t||!t.trim())return null;try{const e=JSON.parse(t);if(Array.isArray(e))return $(e)}catch(t){}return null}function X(t,e,i=!1){if(Array.isArray(t)){let r=!1;for(const n of t){if(!n||"object"!=typeof n||Array.isArray(n))continue;const t=n,o="string"==typeof t.name?t.name.trim():"";if(!o||o in Object.prototype)continue;const a=void 0!==t.value&&null!==t.value?t.value:t.defaultValue;null!=a&&(e[o]=i?"string"==typeof a?a:String(a):a,r=!0)}return r}if(t&&"object"==typeof t&&!Array.isArray(t)){let r=!1;for(const[n,o]of Object.entries(t))if(n&&!(n in Object.prototype)&&o&&"object"==typeof o&&!Array.isArray(o)){const t=o;if("defaultValue"in t||"value"in t||"inputController"in t){const o=void 0!==t.value&&null!==t.value?t.value:t.defaultValue;null!=o&&(e[n]=i?"string"==typeof o?o:String(o):o,r=!0);continue}}return r}return!1}function Y(t,e){const i={};let r=!1;if(Array.isArray(t.componentGroups)){r=!0;for(const e of t.componentGroups){if(!e||"object"!=typeof e)continue;const t=e.components;if(Array.isArray(t))for(const e of t){if(!e||"object"!=typeof e)continue;const t=e;if(Array.isArray(t.propertyGroups))for(const e of t.propertyGroups)e&&"object"==typeof e&&X(e.properties,i,!0);t.properties&&X(t.properties,i,!0)}}}if(Array.isArray(t.propertyGroups)){r=!0;for(const e of t.propertyGroups)e&&"object"==typeof e&&X(e.properties,i,!0)}if(t.properties&&X(t.properties,i,!0)&&(r=!0),r)for(const[t,r]of Object.entries(i))e[t]=String(r);else for(const[i,r]of Object.entries(t))i in Object.prototype||null==r||(e[i]="string"==typeof r?r:JSON.stringify(r))}const Z=new Set(["$schema","id","name","version","contentType","genericContent","contentItems","contentItemsSnapshot","items","options","componentGroups","propertyGroups"]);function K(t,e){let i=null,r=!1;if(t.genericContent&&"object"==typeof t.genericContent&&!Array.isArray(t.genericContent)){r=!0;const i=t.genericContent;if(!X(i.properties,e,!1))for(const[t,r]of Object.entries(i))"properties"===t||"inputController"===t||t in Object.prototype||void 0===r||(e[t]=r)}t.properties&&X(t.properties,e,!1)&&(r=!0);const n=Array.isArray(t.contentItems)?t.contentItems:Array.isArray(t.items)?t.items:Array.isArray(t.contentItemsSnapshot)?t.contentItemsSnapshot:null;n&&(i=$(n));for(const[i,o]of Object.entries(t))i in Object.prototype||void 0===o||"contentItems"!==i&&"items"!==i&&"contentItemsSnapshot"!==i&&"genericContent"!==i&&"design"!==i&&"content"!==i&&"values"!==i&&(r&&(Z.has(i)||"properties"===i)||(!n||"options"!==i&&"contentType"!==i&&"$schema"!==i)&&(e[i]=o));return i}function Q(t){var e;const i=Array.from(t.children).filter((t=>!H(t)&&!G(t)));if(0===i.length)return t.querySelector("[data-widgetic-direct], iframe")||Array.from(t.children).some(G)?(M.delete(t),[]):null!==(e=M.get(t))&&void 0!==e?e:[];const r=i.map(((t,e)=>{var i;t.hasAttribute("data-widgetic-item")||(t.setAttribute("data-widgetic-item","1"),t instanceof HTMLElement&&(t.hidden=!0,t.style.display="none"));const r={};for(const e of Array.from(t.attributes)){const t=e.name.toLowerCase();if("data-widgetic-item"===t||"hidden"===t)continue;if("style"===t&&"display:none;"===e.value.replace(/\s+/g,""))continue;const i=W(e.name);i&&!(i in Object.prototype)&&(r[i]=V(e.value))}if(0===t.children.length){const e=null===(i=t.textContent)||void 0===i?void 0:i.trim();e&&(void 0===r.content&&(r.content=e),void 0===r.text&&(r.text=e))}const n="string"==typeof r.id&&r.id.trim()?r.id:`item-${e+1}`;return Object.assign(Object.assign({id:n,order:e+1},r),{metadata:Object.assign({service:"declarative"},r)})}));return M.set(t,r),r}function tt(t,e){if(!t)return null;if(e in t)return e;const i=e.toLowerCase();for(const e of Object.keys(t))if(e.toLowerCase()===i)return e;return null}function et(t,e){const i=function(t,e){var i;const r={},n={};let o=[];const a=Array.from(t.children).filter(G);for(const t of a){const a=null===(i=t.textContent)||void 0===i?void 0:i.trim();if(!a)continue;let s;try{s=JSON.parse(a)}catch(t){continue}if(Array.isArray(s)){o=$(s);continue}if(!s||"object"!=typeof s)continue;const c=s,u=(t.getAttribute("data-schema")||t.getAttribute("data-widgetic-json")||t.getAttribute("data-widgetic-config")||"").trim().toLowerCase();if("design"===u){Y(c,r);continue}if("content"===u){const t=K(c,n);t&&t.length>0&&(o=t);continue}let l=!1;if(c.design&&"object"==typeof c.design&&!Array.isArray(c.design)&&(Y(c.design,r),l=!0),(Array.isArray(c.componentGroups)||Array.isArray(c.propertyGroups))&&(Y(c,r),l=!0),c.content&&"object"==typeof c.content&&!Array.isArray(c.content)){const t=K(c.content,n);t&&t.length>0&&(o=t),l=!0}if(c.values&&"object"==typeof c.values&&!Array.isArray(c.values)){const t=K(c.values,n);t&&t.length>0&&(o=t),l=!0}if(c.genericContent||Array.isArray(c.contentItems)||Array.isArray(c.items)||Array.isArray(c.contentItemsSnapshot)){const t=K(c,n);t&&t.length>0&&(o=t),l=!0}if(!l)for(const[t,i]of Object.entries(c)){if(t in Object.prototype||null==i)continue;const o=tt(null==e?void 0:e.content,t),a=tt(null==e?void 0:e.design,t);a&&!o?r[a]="string"==typeof i?i:JSON.stringify(i):o&&!a?n[o]=i:(n[t]=i,"string"!=typeof i&&"number"!=typeof i||(r[t]=String(i)))}}return{design:r,content:n,contentItems:o}}(t,e),r=Object.assign({},i.design),n=Object.assign({},i.content);let o=null;const a=J(t.getAttribute("design"));a&&Y(a,r);const s=J(t.getAttribute("content"));if(s){const t=K(s,n);t&&t.length>0&&(o=t)}const c=J(t.getAttribute("values"));if(c){const t=K(c,n);t&&t.length>0&&(o=t)}for(const i of Array.from(t.attributes)){const t=i.name,o=t.toLowerCase();if(o.startsWith("design-")&&o.length>7){const n=W(t.slice(7));if(n&&!(n in Object.prototype)){r[tt(null==e?void 0:e.design,n)||n]=i.value}continue}if(o.startsWith("content-")&&"content-items"!==o&&o.length>8){const r=W(t.slice(8));if(r&&!(r in Object.prototype)){n[tt(null==e?void 0:e.content,r)||r]=V(i.value)}continue}if(B(t))continue;const a=W(t);if(!a||a in Object.prototype)continue;const s=tt(null==e?void 0:e.content,a),c=tt(null==e?void 0:e.design,a);if(s&&!c)n[s]=V(i.value);else if(c&&!s)r[c]=i.value;else{r[a]=i.value,n[a]=V(i.value);const e=t.replace(/^data-/,"");e===a||e in Object.prototype||(r[e]=i.value)}}let u=Q(t);if(0===u.length){const e=U(t.getAttribute("content-items"))||U(t.getAttribute("contentitems"))||U(t.getAttribute("items"))||o;e&&e.length>0?u=e:i.contentItems.length>0&&(u=i.contentItems)}return{design:r,content:n,contentItems:u,hasOverrides:Object.keys(r).length>0||Object.keys(n).length>0||u.length>0}}function it(t,e){const i=null!=e?e:{},r=et(t,i);return r.hasOverrides?Object.assign(Object.assign({},i),{design:Object.assign(Object.assign({},i.design||{}),r.design),content:Object.assign(Object.assign({},i.content||{}),r.content),contentItems:r.contentItems.length>0?r.contentItems:i.contentItems||[]}):i}function rt(t){var e,i;if(0===t.length)return!0;for(const r of t){if("attributes"===r.type){const t=(null===(e=r.attributeName)||void 0===e?void 0:e.toLowerCase())||"";if(!t)continue;if("data-widgetic-mounted"===t||"data-widgetic-mounting"===t||"data-widgetic-refused"===t||"data-widgetic-context-invalid"===t||"data-widgetic-overlay"===t||"data-device-restricted"===t||"data-widgetic-item"===t||"hidden"===t)continue;if("style"===t&&r.target!==(null===(i=r.target.ownerDocument)||void 0===i?void 0:i.body)&&r.target instanceof Element&&r.target.hasAttribute("data-widgetic-item"))continue;if(r.target instanceof Element&&H(r.target))continue;return!0}if("childList"===r.type){if(r.target instanceof Element&&H(r.target))continue;if([...Array.from(r.addedNodes),...Array.from(r.removedNodes)].some((t=>!(t instanceof Element&&H(t)))))return!0}if("characterData"===r.type){const t=r.target.parentElement;if(t&&!H(t))return!0}}return!1}const nt=new WeakMap;function ot(t,e,i){const r=nt.get(t);r&&r();const n="undefined"!=typeof MutationObserver?MutationObserver:null;if(!n)return()=>{};let o,a=!1;try{o=new n((r=>{rt(r)&&(a||(a=!0,queueMicrotask((()=>{a=!1;const r=et(t,e);i(r)}))))}))}catch(t){return()=>{}}o.observe(t,{attributes:!0,childList:!0,subtree:!0,characterData:!0});const s=()=>{o.disconnect(),nt.delete(t)};return nt.set(t,s),s}function at(t){const e=nt.get(t);e&&e()}function st(){return"undefined"==typeof window?{customElements:!1,http3:!1,resizeObserver:!1,fullscreenApi:!1,popupBlocking:!1}:{customElements:"undefined"!=typeof customElements&&"function"==typeof customElements.define,http3:ct(),resizeObserver:"undefined"!=typeof ResizeObserver,fullscreenApi:ut(),popupBlocking:lt()}}function ct(){if("undefined"==typeof performance||!performance.getEntriesByType)return!1;try{const t=performance.getEntriesByType("navigation");if(t.length>0){const e=t[0];return"h3"===e.nextHopProtocol||"h3-29"===e.nextHopProtocol}return!1}catch(t){return!1}}function ut(){return!("undefined"==typeof document||!document.documentElement)&&!!(document.documentElement.requestFullscreen||document.documentElement.webkitRequestFullscreen||document.documentElement.mozRequestFullScreen||document.documentElement.msRequestFullscreen)}function lt(){if("undefined"==typeof window||!window.open)return!1;try{const t=window.open("","widgetic-popup-test","width=1,height=1");return!t||(t.close(),!1)}catch(t){return!0}}function dt(t,e){switch(t){case"custom-element":case"auto":default:return e.customElements?"custom-element":"iframe";case"iframe":return"iframe"}}function pt(){if("undefined"==typeof localStorage)return!1;try{const t="widgetic-test";return localStorage.setItem(t,t),localStorage.removeItem(t),!0}catch(t){return!1}}var gt=Object.freeze({__proto__:null,checkSdkInitialization:function(){if("undefined"==typeof window)return!1;const t="widgetic-sdk-initialized";return pt()?!!localStorage.getItem(t)||(localStorage.setItem(t,Date.now().toString()),!1):!!window.__widgeticInitialized},clearSdkInitialization:function(){pt()&&localStorage.removeItem("widgetic-sdk-initialized"),delete window.__widgeticInitialized},detectBrowserCapabilities:st,determineBestRenderMode:dt,hasIntersectionObserver:function(){return"undefined"!=typeof IntersectionObserver},isLocalStorageAvailable:pt});class bt{static analyzeElement(t){try{const e=this.getExplicitMetadata(t);return e||this.analyzeHeuristically(t)}catch(t){return null}}static getExplicitMetadata(t){const e=t.getAttribute("data-widget-meta");if(e)try{return JSON.parse(e)}catch(t){}const i=t.getAttribute("data-capabilities");if(i)return this.parseCapabilitiesString(i);const r=t.querySelector('script[type="application/json"]');if(r&&r.textContent)try{const t=JSON.parse(r.textContent);return t.capabilities||t.metadata}catch(t){}return null}static analyzeHeuristically(t){const e={type:"custom",version:"1.0.0"},i=t.getAttribute("data-widget-type")||t.getAttribute("data-type")||this.inferTypeFromStructure(t);switch(i&&(e.type=i),e.type){case"media":e.mediaCapabilities=this.analyzeMediaCapabilities(t);break;case"gallery":e.contentCapabilities=this.analyzeContentCapabilities(t);break;case"form":e.textCapabilities=this.analyzeTextCapabilities(t);break;case"interactive":e.interactionCapabilities=this.analyzeInteractionCapabilities(t)}return e.supportsResponsive=this.checkResponsiveSupport(t),e.supportsAutoscale=this.checkAutoscaleSupport(t),e.supportsThemes=this.checkThemeSupport(t),e.displayCapabilities=this.analyzeDisplayCapabilities(t),e.abTestingCapabilities=this.analyzeABTestingCapabilities(t),e}static inferTypeFromStructure(t){var e;return t.querySelector("video, audio")||t.classList.contains("media-widget")||(null===(e=t.getAttribute("data-widget-id"))||void 0===e?void 0:e.includes("video"))?"media":t.querySelector("form, input, textarea")||t.classList.contains("form-widget")?"form":t.querySelector(".gallery, .carousel")||t.classList.contains("gallery-widget")||t.querySelectorAll("img").length>1?"gallery":t.querySelector("button, .interactive")||t.classList.contains("quiz-widget")||t.classList.contains("poll-widget")?"interactive":"custom"}static analyzeMediaCapabilities(t){const e=t.querySelectorAll("video"),i=t.querySelectorAll("audio"),r=null!==t.querySelector("[controls]"),n=null!==t.querySelector("[data-volume], .volume-control");let o="audio";return e.length>0&&i.length>0?o="mixed":e.length>0&&(o="video"),{supportsPlay:!0,supportsPause:!0,supportsVolumeControl:n||r,supportsSeek:r,supportsGlobalVolume:t.hasAttribute("data-global-volume"),mediaType:o}}static analyzeContentCapabilities(t){const e=t.querySelectorAll(".item, .slide, img, .content-item"),i=null!==t.querySelector(".nav, .navigation, button"),r=t.hasAttribute("data-position")||t.hasAttribute("data-track-position");let n="gallery";return t.classList.contains("carousel")&&(n="carousel"),t.classList.contains("list")&&(n="list"),t.classList.contains("grid")&&(n="grid"),{supportsPositionTracking:r,supportsNavigation:i,contentType:n,totalItems:e.length}}static analyzeTextCapabilities(t){const e=t.querySelectorAll("input, textarea, select"),i=Array.from(e).map((t=>t.getAttribute("name")||t.getAttribute("id")||"unknown"));return{supportsTextPersistence:t.hasAttribute("data-persist")||t.hasAttribute("data-autosave"),supportsSanitization:!0,fields:i}}static analyzeInteractionCapabilities(t){const e=t.querySelectorAll("button").length>0,i=t.querySelectorAll("form").length>0,r=t.hasAttribute("data-events")||t.hasAttribute("data-track-interactions"),n=[],o=t.getAttribute("data-events");return o&&n.push(...o.split(",").map((t=>t.trim()))),{supportsClicks:e||null!==t.querySelector("[onclick]"),supportsFormSubmission:i,supportsCustomEvents:r,customEventTypes:n.length>0?n:void 0}}static analyzeDisplayCapabilities(t){return{supportsFullscreen:t.hasAttribute("data-fullscreen")||t.classList.contains("fullscreen-capable"),supportsOverlay:t.hasAttribute("data-overlay")||t.classList.contains("overlay-capable"),supportsPopup:t.hasAttribute("data-popup")||t.classList.contains("popup-capable"),supportsInline:!0}}static analyzeABTestingCapabilities(t){if(!("widgetic-abtest"===t.tagName.toLowerCase()||t.hasAttribute("experiment-id")||t.hasAttribute("data-ab-test")))return;const e=[],i=[];return t.querySelector("button, a, [onclick]")&&(e.push("clicks"),i.push("clicks")),t.querySelector("form")&&(e.push("submissions"),i.push("conversions")),t.querySelector("video, audio")&&(e.push("plays"),i.push("plays")),e.push("impressions"),{supportsTracking:!0,trackableEvents:e,conversionGoals:i}}static checkResponsiveSupport(t){return t.hasAttribute("data-responsive")||t.hasAttribute("data-breakpoints")||t.classList.contains("responsive")}static checkAutoscaleSupport(t){return t.hasAttribute("data-autoscale")||t.hasAttribute("data-auto-height")||t.classList.contains("autoscale")}static checkThemeSupport(t){return t.hasAttribute("data-theme")||t.classList.contains("themeable")||null!==t.querySelector("[data-theme]")}static parseCapabilitiesString(t){const e=t.split(",").map((t=>t.trim()));return{type:"custom",version:"1.0.0",mediaCapabilities:e.includes("media")?{supportsPlay:!0,supportsPause:!0,supportsVolumeControl:e.includes("volume"),supportsSeek:e.includes("seek"),supportsGlobalVolume:e.includes("global-volume"),mediaType:"mixed"}:void 0,textCapabilities:e.includes("forms")?{supportsTextPersistence:e.includes("persist"),supportsSanitization:!0,fields:[]}:void 0,interactionCapabilities:e.includes("interactive")?{supportsClicks:!0,supportsFormSubmission:e.includes("forms"),supportsCustomEvents:e.includes("events")}:void 0,supportsResponsive:e.includes("responsive"),supportsAutoscale:e.includes("autoscale"),supportsThemes:e.includes("themes")}}}function ft(t){var e,i,r,n;const o=new Set;return o.add("rendering"),o.add("api"),t.mediaCapabilities&&o.add("media"),t.textCapabilities&&o.add("security"),t.interactionCapabilities&&o.add("messaging"),((null===(e=t.displayCapabilities)||void 0===e?void 0:e.supportsFullscreen)||(null===(i=t.displayCapabilities)||void 0===i?void 0:i.supportsOverlay)||(null===(r=t.displayCapabilities)||void 0===r?void 0:r.supportsPopup))&&o.add("display"),t.abTestingCapabilities&&(o.add("abTesting"),o.add("messaging")),(null===(n=t.performanceRequirements)||void 0===n?void 0:n.requiresLazyLoading)&&o.add("performance"),Array.from(o)}var mt=Object.freeze({__proto__:null,WidgetMetadataAnalyzer:bt,analyzeWidgetRequirementsEnhanced:function(t){const e=new Set;for(const i of t){const t=bt.analyzeElement(i);if(t){ft(t).forEach((t=>e.add(t)))}}return Array.from(e)},getRequiredChunks:ft});export{e as D,r as M,_ as a,et as b,F as c,Q as d,i as e,st as f,D as g,rt as h,pt as i,O as j,dt as k,C as l,it as m,L as n,ot as o,n as p,gt as q,at as s,mt as w};
@@ -1 +1 @@
1
- import{_ as e}from"./vendor.js";import{l as t}from"./core.js";import{k as i}from"./scanner.js";class n{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(),t.info("[SecurityManager] Initialized with config:",this.config)}static getInstance(e){return n.instance||(n.instance=new n(e)),n.instance}validateTextFieldUpdate(e,t,i,n){const s=`${e}:${t}`;if(this.blockedInstances.has(e))return{allowed:!1,reason:"Instance blocked due to security violations",severity:"high"};if(i.length>this.config.maxTextLength)return this.recordViolation(e,"text_length_exceeded"),{allowed:!1,reason:`Text length exceeds maximum (${this.config.maxTextLength} characters)`,severity:"medium"};if(this.config.enableRateLimit){const t=this.checkRateLimit(s);if(!t.allowed)return this.recordViolation(e,"rate_limit_exceeded"),t}if(this.config.enableBotDetection){const t=this.analyzeBehavior(e,i);if(!t.allowed)return this.recordViolation(e,"suspicious_behavior"),t}let a=i;if(this.config.enableSanitization){const t=this.sanitizeInput(i);if(!t.allowed)return this.recordViolation(e,"malicious_content"),t;a=t.sanitizedText||i}const r=this.analyzeContentPatterns(i);return r.allowed?{allowed:!0,sanitizedText:a}:(this.recordViolation(e,"suspicious_pattern"),r)}sanitizeInput(e){try{const t=/javascript:/gi,i=/\bon\w+\s*=/gi,n=/data:text\/html/gi;if(/<script[^>]*>[\s\S]*?<\/script>/gi.test(e)||t.test(e)||i.test(e)||n.test(e))return{allowed:!1,reason:"Potentially malicious content detected",severity:"high"};let s=e.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/javascript:/gi,"").replace(/\bon\w+\s*=/gi,"").replace(/data:text\/html/gi,"data:text/plain");s=this.sanitizeLinks(s);const a=(s.match(/<[a-z][^>]*>/gi)||[]).length,r=s.replace(/<[^>]+>/g,"").length;if(a>0&&r>0){if(a/r>.1)return{allowed:!1,reason:"Excessive HTML content detected",severity:"medium"}}return{allowed:!0,sanitizedText:s}}catch(e){return t.warn("[SecurityManager] Sanitization error:",e),{allowed:!1,reason:"Input sanitization failed",severity:"medium"}}}sanitizeLinks(e){try{const t=/<a\b(?![^>]*\bhref\s*=)[^>]*>/gi,i=e.replace(/<a\b(?![^>]*\bhref\s*=)[^>]*>([\s\S]*?)<\/a>/gi,"$1").replace(t,""),n=/<a\s+([^>]*href\s*=\s*["'][^"']*["'][^>]*)>/gi;return i.replace(n,((e,t)=>{const i=t.match(/href\s*=\s*["']([^"']*)["']/i);if(!i)return"";const n=i[1],s=["javascript:","data:","vbscript:","file:","ftp:"];for(const e of s)if(n.toLowerCase().startsWith(e))return"";const a=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+=a?' target="_blank" rel="nofollow noopener noreferrer"':' rel="noopener"',`<a ${r}>`}))}catch(i){return t.warn("[SecurityManager] Link sanitization error:",i),e}}isExternalLink(e){try{if(e.startsWith("//"))return!0;if(e.startsWith("/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("#")||e.startsWith("?"))return!1;if(e.includes("://")){const t=new URL(e),i="undefined"!=typeof window?window.location.hostname:"";return t.hostname!==i}return!1}catch(e){return!0}}checkRateLimit(e){const t=Date.now(),i=this.rateLimitTracker.get(e)||{count:0,windowStart:t,violations:0};return t-i.windowStart>=6e4&&(i.count=0,i.windowStart=t),i.count++,this.rateLimitTracker.set(e,i),i.count>this.config.maxUpdatesPerMinute?(i.violations++,{allowed:!1,reason:"Rate limit exceeded for this widget",severity:"medium"}):(t-this.globalRateLimit.windowStart>=6e4&&(this.globalRateLimit.count=0,this.globalRateLimit.windowStart=t),this.globalRateLimit.count++,this.globalRateLimit.count>this.config.maxGlobalUpdatesPerMinute?(this.globalRateLimit.violations++,{allowed:!1,reason:"Global rate limit exceeded",severity:"high"}):{allowed:!0})}analyzeBehavior(e,t){const i=Date.now(),n=this.behaviorTracker.get(e)||{updateCount:0,averageInterval:0,suspiciousPatterns:0,firstSeen:i,lastSeen:i,textLengthVariations:[],updateIntervals:[]},s=i-n.lastSeen;if(n.updateIntervals.push(s),n.textLengthVariations.push(t.length),n.updateIntervals.length>20&&(n.updateIntervals=n.updateIntervals.slice(-20),n.textLengthVariations=n.textLengthVariations.slice(-20)),n.updateCount++,n.lastSeen=i,n.updateIntervals.length>1){const e=n.updateIntervals.filter((e=>e>0));n.averageInterval=e.reduce(((e,t)=>e+t),0)/e.length}let a=0;if(n.updateIntervals.length>=5){const e=n.updateIntervals.slice(-5);this.calculateVariance(e)<100&&a++}if(n.updateIntervals.length>=3){n.updateIntervals.slice(-3).every((e=>e<100&&e>0))&&a++}if(n.textLengthVariations.length>=5){const e=n.textLengthVariations.slice(-5);1===new Set(e).size&&e[0]>10&&a++}const r=i-n.firstSeen;if(r>0&&n.updateCount>50){n.updateCount/(r/1e3)>2&&a++}if(n.suspiciousPatterns=a,this.behaviorTracker.set(e,n),a>=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,i){t.warn(`[SecurityManager] Security violation: ${i}`,{instanceId:e});const n=`${e}:violations`,s=this.rateLimitTracker.get(n)||{count:0,windowStart:Date.now(),violations:0};s.violations++,this.rateLimitTracker.set(n,s),s.violations>=10&&(this.blockedInstances.add(e),t.warn(`[SecurityManager] Blocked instance due to repeated violations: ${e}`)),"undefined"!=typeof document&&document.dispatchEvent(new CustomEvent("widgetic:security-violation",{detail:{instanceId:e,violationType:i,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(),i=18e5;for(const[t,n]of this.rateLimitTracker.entries())e-n.windowStart>i&&this.rateLimitTracker.delete(t);for(const[t,n]of this.behaviorTracker.entries())e-n.lastSeen>i&&this.behaviorTracker.delete(t);t.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);t.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),t.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(),t.info("[SecurityManager] Destroyed")}}function s(e){return n.getInstance(e)}var a=Object.freeze({__proto__:null,SecurityManager:n,getSecurityManager:s});class r{constructor(e={}){var i,s,a,r;this.cspDirectives=new Map,this.cspNonce="",this.encryptionKey=null,this.sensitiveDataCache=new Map,this.contentFilters=new Map,this.moderationQueue=new Map,this.auditEvents=[],this.auditBuffer=new Map,this.threatPatterns=new Map,this.threatScores=new Map,this.consentStatus=new Map,this.dataSubjects=new Map,this.config=Object.assign({enableSanitization:!0,enableRateLimit:!0,enableBotDetection:!0,maxTextLength:1e5,maxUpdatesPerMinute:60,maxGlobalUpdatesPerMinute:1e3,suspiciousActivityThreshold:5,auditLogging:!0,threatDetection:!0,csp:{level:"balanced",allowInlineStyles:!1,allowEval:!1,reportOnly:!1},secureData:{classification:"internal",encryptInTransit:!0,encryptAtRest:!1,anonymizeData:!1,dataRetentionDays:90},contentFilter:{enableProfanityFilter:!0,enableSpamDetection:!0,enableMalwareScanning:!0,autoModeration:!1},privacy:{enableGDPRCompliance:!0,enableCCPACompliance:!0,anonymizeUserData:!1,cookieConsent:!0,dataProcessingBasis:"legitimate_interest",dataSubjectRights:!0}},e),this.baseSecurityManager=n.getInstance(this.config),this.initializeCSP(),this.initializeDataSecurity(),this.initializeContentFilters(),this.initializeThreatDetection(),this.initializePrivacyControls(),t.info("[AdvancedSecurityManager] Initialized with config:",{cspLevel:null===(i=this.config.csp)||void 0===i?void 0:i.level,dataClassification:null===(s=this.config.secureData)||void 0===s?void 0:s.classification,contentFiltering:null===(a=this.config.contentFilter)||void 0===a?void 0:a.enableProfanityFilter,privacy:null===(r=this.config.privacy)||void 0===r?void 0:r.enableGDPRCompliance})}static getInstance(e){return r.instance||(r.instance=new r(e)),r.instance}initializeCSP(){this.config.csp&&(this.cspNonce=this.generateNonce(),this.setupCSPDirectives(),this.applyCSP(),t.info("[AdvancedSecurityManager] CSP initialized with level:",this.config.csp.level))}generateNonce(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}setupCSPDirectives(){var e,t;const{level:i,allowedDomains:n=[],allowInlineStyles:s,allowEval:a}=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,...a?["'unsafe-eval'"]:[]]),this.cspDirectives.set("style-src",["'self'",`'nonce-${this.cspNonce}'`,...r,...s?["'unsafe-inline'"]:[]]),this.cspDirectives.set("img-src",["'self'","data:","blob:","https:",...r]),this.cspDirectives.set("connect-src",["'self'",...r]),this.cspDirectives.set("font-src",["'self'","https:",...r]),this.cspDirectives.set("media-src",["'self'","blob:","https:",...r]),this.cspDirectives.set("object-src",["'none'"]),this.cspDirectives.set("base-uri",["'self'"]),this.cspDirectives.set("form-action",["'self'",...r]),this.cspDirectives.set("frame-ancestors",["'self'",...r]);break;case"permissive":this.cspDirectives.set("default-src",["'self'",...r,"https:"]),this.cspDirectives.set("script-src",["'self'","'unsafe-inline'","'unsafe-eval'",...r,"https:"]),this.cspDirectives.set("style-src",["'self'","'unsafe-inline'",...r,"https:"]),this.cspDirectives.set("img-src",["*","data:","blob:"]),this.cspDirectives.set("connect-src",["*"]),this.cspDirectives.set("font-src",["*"]),this.cspDirectives.set("media-src",["*"]),this.cspDirectives.set("object-src",["'none'"]),this.cspDirectives.set("base-uri",["'self'"]),this.cspDirectives.set("form-action",["*"])}(null===(e=this.config.csp)||void 0===e?void 0:e.customDirectives)&&Object.entries(this.config.csp.customDirectives).forEach((([e,t])=>{this.cspDirectives.set(e,t)})),(null===(t=this.config.csp)||void 0===t?void 0:t.reportUri)&&this.cspDirectives.set("report-uri",[this.config.csp.reportUri])}applyCSP(){var e;if("undefined"==typeof document)return;const i=this.buildCSPString();let n=document.querySelector('meta[http-equiv="Content-Security-Policy"]');n||(n=document.createElement("meta"),n.httpEquiv="Content-Security-Policy",document.head.appendChild(n)),(null===(e=this.config.csp)||void 0===e?void 0:e.reportOnly)&&(n.httpEquiv="Content-Security-Policy-Report-Only"),n.content=i,t.info("[AdvancedSecurityManager] CSP applied:",i)}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 e(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"]),t.info("[AdvancedSecurityManager] Data encryption initialized")}catch(e){t.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)})),t.info("[AdvancedSecurityManager] Content filtering initialized with filters:",Array.from(this.contentFilters.keys())))}addDefaultContentFilters(){var t,i,n;(null===(t=this.config.contentFilter)||void 0===t?void 0:t.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:(t,i)=>e(this,void 0,void 0,(function*(){return this.detectLinkSpam(t)}))})),(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)})),t.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(),t.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){t.warn("[AdvancedSecurityManager] Failed to parse existing consent:",e)}}}initializeDataSubjectRights(){t.info("[AdvancedSecurityManager] Data subject rights initialized")}validateContent(i,n){return e(this,arguments,void 0,(function*(e,i,n={}){var s;const a=[];let r=i;try{const t=this.baseSecurityManager.validateTextFieldUpdate(e,n.fieldId||"content",i,n);if(!t.allowed)return a.push({filterId:"basic_security",filterName:"Basic Security",severity:t.severity||"medium",reason:t.reason||"Basic security validation failed"}),yield this.logAuditEvent({type:"security_violation",widgetId:e,action:"content_validation",outcome:"blocked",details:{reason:t.reason,contentLength:i.length},classification:"internal",severity:"medium",userId:n.userId,sessionId:n.sessionId}),{allowed:!1,violations:a};if(t.sanitizedText&&(r=t.sanitizedText),this.config.threatDetection){const t=yield this.detectThreats(e,r,n);if(t.violations.length>0){if(a.push(...t.violations),!t.allowed)return{allowed:!1,violations:a};t.filteredContent&&(r=t.filteredContent)}}if(this.config.contentFilter){const t=yield this.applyContentFilters(r,n);if(t.violations.length>0){if(a.push(...t.violations),!t.allowed)return yield this.logAuditEvent({type:"content_filtered",widgetId:e,action:"content_blocked",outcome:"blocked",details:{violations:t.violations,originalLength:i.length},classification:"internal",severity:"medium",userId:n.userId,sessionId:n.sessionId}),{allowed:!1,violations:a};t.filteredContent&&(r=t.filteredContent)}}return 0===a.length&&(yield this.logAuditEvent({type:"data_accessed",widgetId:e,action:"content_validated",outcome:"success",details:{contentLength:i.length,filtered:r!==i},classification:(null===(s=this.config.secureData)||void 0===s?void 0:s.classification)||"internal",severity:"low",userId:n.userId,sessionId:n.sessionId})),{allowed:!0,filteredContent:r!==i?r:void 0,violations:a}}catch(i){return t.error("[AdvancedSecurityManager] Content validation error:",i),yield this.logAuditEvent({type:"security_violation",widgetId:e,action:"content_validation_error",outcome:"failure",details:{error:i instanceof Error?i.message:"Unknown error"},classification:"internal",severity:"high",userId:n.userId,sessionId:n.sessionId}),a.push({filterId:"system_error",filterName:"System Error",severity:"critical",reason:"Content validation system error"}),{allowed:!1,violations:a}}}))}applyContentFilters(i,n){return e(this,void 0,void 0,(function*(){const e=[];let s=i,a=!1;for(const[i,r]of this.contentFilters)try{const t=yield this.applyFilter(r,s,n);if(t.violations&&e.push(...t.violations),!t.allowed){if("block"===r.action){a=!0;break}"moderate"===r.action&&this.moderationQueue.set(`${Date.now()}-${i}`,{content:s,filter:r,context:n,timestamp:Date.now()})}t.filteredContent&&(s=t.filteredContent)}catch(n){t.error(`[AdvancedSecurityManager] Filter ${i} error:`,n),e.push({filterId:i,filterName:r.name,severity:"medium",reason:"Filter processing error"})}return{allowed:!a,filteredContent:s!==i?s:void 0,violations:e}}))}applyFilter(t,i,n){return e(this,void 0,void 0,(function*(){switch(t.type){case"regex":return this.applyRegexFilter(t,i);case"keyword":return this.applyKeywordFilter(t,i);case"custom":return t.customHandler?yield t.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 s=n.map((t=>({filterId:e.id,filterName:e.name,severity:e.severity,reason:`Pattern matched: ${t}`}))),a=t.replace(i,"[FILTERED]");return{allowed:"block"!==e.action,filtered:!0,filteredContent:a,violations:s,confidence:.9}}return{allowed:!0}}applyKeywordFilter(e,t){if(!e.keywords||0===e.keywords.length)return{allowed:!0};const i=t.toLowerCase(),n=[];let s=t;for(const t of e.keywords){const a=t.toLowerCase();if(i.includes(a)){n.push({filterId:e.id,filterName:e.name,severity:e.severity,reason:`Keyword detected: ${t}`});const i=new RegExp(t,"gi");s=s.replace(i,"[FILTERED]")}}return n.length>0?{allowed:"block"!==e.action,filtered:!0,filteredContent:s,violations:n,confidence:.8}:{allowed:!0}}detectLinkSpam(i){return e(this,void 0,void 0,(function*(){const e=[];let n=0;try{const t=/<a[^>]*href\s*=\s*["']([^"']*)["'][^>]*>([^<]*)<\/a>/gi,s=[];let a;for(;null!==(a=t.exec(i));)s.push({url:a[1],text:a[2],match:a[0]});s.length>5&&(n+=3,e.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"medium",reason:`Excessive number of links detected: ${s.length}`}));for(const t of s){["bit.ly","tinyurl","t.co","goo.gl","ow.ly","tiny.cc"].some((e=>t.url.includes(e)))&&(n+=2,e.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"medium",reason:`URL shortener detected: ${t.url}`}));["click here","read more","visit now","buy now","order now","download now","get started","try free","join now","sign up"].some((e=>t.text.toLowerCase().includes(e.toLowerCase())))&&(n+=1,e.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"low",reason:`Suspicious link text: "${t.text}"`}));[".tk",".ml",".ga",".cf",".buzz",".click"].some((e=>t.url.includes(e)))&&(n+=2,e.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"medium",reason:`Suspicious domain: ${t.url}`})),t.text.includes("http")&&!t.url.includes(t.text.replace(/^https?:\/\//,""))&&(n+=3,e.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"high",reason:`Mismatched link text and URL: "${t.text}" -> ${t.url}`}))}const r=n>=5,o=Math.min(n/10,1);return{allowed:!r,filtered:e.length>0,violations:e,confidence:o,requiresModeration:n>=3&&n<5}}catch(e){return t.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(t,i,n){return e(this,void 0,void 0,(function*(){const e=[];let s=0,a=!1;for(const[r,o]of this.threatPatterns){let c=0;for(const e of o.indicators){c+=this.evaluateIndicator(e,i,n)}const l=Math.min(10,c);s+=l,l>=7&&(e.push({filterId:r,filterName:o.name,severity:o.severity,reason:o.description}),"block"!==o.responseAction&&"quarantine"!==o.responseAction||(a=!0),yield this.logAuditEvent({type:"threat_detected",widgetId:t,action:"threat_pattern_matched",outcome:a?"blocked":"suspicious",details:{patternId:r,patternName:o.name,threatScore:l,indicators:o.indicators.length},classification:"confidential",severity:o.severity,userId:n.userId,sessionId:n.sessionId}))}const r=`${t}:${n.userId||"anonymous"}`;return this.threatScores.set(r,(this.threatScores.get(r)||0)+s),{allowed:!a,violations:e}}))}evaluateIndicator(e,i,n){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(i)?e.weight:0}break;case"content":if("function"==typeof e.condition)return e.condition(i)?e.weight:0;break;case"behavior":case"frequency":if("function"==typeof e.condition)return e.condition(n)?e.weight:0}return 0}catch(e){return t.warn("[AdvancedSecurityManager] Indicator evaluation error:",e),0}}logAuditEvent(i){return e(this,void 0,void 0,(function*(){if(!this.config.auditLogging)return;const e=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:{}},i),n=e.widgetId;this.auditBuffer.has(n)||this.auditBuffer.set(n,[]),this.auditBuffer.get(n).push(e),this.auditEvents.push(e),this.auditEvents.length>1e3&&this.auditEvents.splice(0,this.auditEvents.length-1e3);const s=this.getLogLevel(e.severity);t[s](`[SecurityAudit] ${e.type}:`,{id:e.id,widgetId:e.widgetId,action:e.action,outcome:e.outcome,severity:e.severity,userId:e.userId}),"undefined"!=typeof document&&document.dispatchEvent(new CustomEvent("widgetic:security-audit",{detail:e}))}))}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,i,n,s={}){if(this.consentStatus.set(i,n),"undefined"!=typeof localStorage){const e=JSON.parse(localStorage.getItem("widgetic_privacy_consent")||"{}");e[i]=n,e.timestamp=Date.now(),localStorage.setItem("widgetic_privacy_consent",JSON.stringify(e))}this.logAuditEvent({type:"privacy_consent",widgetId:e,action:"consent_"+(n?"granted":"revoked"),outcome:"success",details:{consentType:i,granted:n},classification:"confidential",severity:"medium",userId:s.userId,sessionId:s.sessionId}),t.info(`[AdvancedSecurityManager] Privacy consent ${n?"granted":"revoked"}:`,{consentType:i,widgetId:e,userId:s.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"}}}function o(e){return r.getInstance(e)}var c=Object.freeze({__proto__:null,AdvancedSecurityManager:r,getAdvancedSecurityManager:o});class l{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=s(),this.initialize()}static getInstance(){return l.instance||(l.instance=new l),l.instance}initialize(){this.initialized||(i()?(this.loadStoredState(),this.cleanupOldEntries(),this.initialized=!0,t.info("[TextFieldManager] Initialized successfully")):t.warn("[TextFieldManager] localStorage not available, text persistence disabled"))}registerTextField(e,i,n={}){const s=this.generateStateKey(e,i);t.debug(`[TextFieldManager] Registering text field: ${e}.${i}`,{config:n});const a=this.textStates.get(s);return a&&n.autoRestore&&this.shouldAutoRestore(a,n)&&t.debug(`[TextFieldManager] Auto-restoring text for ${s}`,{textLength:a.text.length,lastModified:new Date(a.lastModified)}),s}updateTextField(e,i,n,s={},a){const r=this.securityManager.validateTextFieldUpdate(e,i,n,a);if(!r.allowed)return t.warn(`[TextFieldManager] Security validation failed for ${e}.${i}`,{reason:r.reason,severity:r.severity}),void("undefined"!=typeof document&&document.dispatchEvent(new CustomEvent("widgetic:text-field-security-blocked",{detail:{instanceId:e,fieldId:i,reason:r.reason,severity:r.severity,originalTextLength:n.length,timestamp:Date.now()}})));const o=r.sanitizedText||n,c=this.generateStateKey(e,i);let l=o;s.maxLength&&o.length>s.maxLength&&(t.warn(`[TextFieldManager] Text exceeds maxLength (${s.maxLength}), truncating`),l=o.substring(0,s.maxLength));const d={instanceId:e,fieldId:i,text:l,lastModified:Date.now(),textType:s.textType||"custom",metadata:Object.assign(Object.assign({},a),{characterCount:l.length,wordCount:this.countWords(l),sanitized:o!==n})};this.textStates.set(c,d),s.autoPersist&&s.persistState&&this.debouncePersist(c,s.debounceDelay||1e3),t.debug(`[TextFieldManager] Updated text field: ${c}`,{textLength:l.length,textType:d.textType,sanitized:o!==n})}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,i){const n=this.generateStateKey(e,i);this.textStates.delete(n),this.clearDebounceTimer(n),this.persistState(),t.debug(`[TextFieldManager] Cleared text field: ${n}`)}clearWidgetTextFields(e){const i=[];for(const[t,n]of this.textStates)n.instanceId===e&&i.push(t);i.forEach((e=>{this.textStates.delete(e),this.clearDebounceTimer(e)})),this.persistState(),t.debug(`[TextFieldManager] Cleared ${i.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 i=JSON.parse(e);if(i.version!==this.storageVersion)return t.info("[TextFieldManager] Storage version mismatch, clearing stored data"),void localStorage.removeItem(this.storageKey);i.textStates&&(this.textStates=new Map(Object.entries(i.textStates)),t.debug(`[TextFieldManager] Loaded ${this.textStates.size} text field states from storage`)),"boolean"==typeof i.autoRestoreEnabled&&(this.autoRestoreEnabled=i.autoRestoreEnabled)}catch(e){t.warn("[TextFieldManager] Failed to load stored state:",e),localStorage.removeItem(this.storageKey)}}persistState(){if(i())try{const e={version:this.storageVersion,textStates:Object.fromEntries(this.textStates),timestamp:Date.now(),autoRestoreEnabled:this.autoRestoreEnabled};localStorage.setItem(this.storageKey,JSON.stringify(e)),t.debug(`[TextFieldManager] Persisted state for ${this.textStates.size} text fields`)}catch(e){t.warn("[TextFieldManager] Failed to persist state:",e)}}cleanupOldEntries(){const e=Date.now()-this.maxStorageAge,i=[];for(const[t,n]of this.textStates)n.lastModified<e&&i.push(t);i.length>0&&(i.forEach((e=>this.textStates.delete(e))),this.persistState(),t.debug(`[TextFieldManager] Cleaned up ${i.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(),t.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(),i()&&localStorage.removeItem(this.storageKey),t.debug("[TextFieldManager] Cleaned up all data")}configureSecurity(e){this.securityManager.updateConfig(e),t.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),t.info(`[TextFieldManager] Unblocked instance: ${e}`)}getSecurityStats(){return this.securityManager.getSecurityStats()}validateText(e,t,i,n){return this.securityManager.validateTextFieldUpdate(e,t,i,n)}}function d(){return l.getInstance()}var u=Object.freeze({__proto__:null,TextFieldManager:l,getTextField:function(e,t){return d().getTextField(e,t)},getTextFieldManager:d,registerTextField:function(e,t,i){return d().registerTextField(e,t,i)},updateTextField:function(e,t,i,n,s){d().updateTextField(e,t,i,n,s)}});export{n as S,c as a,o as g,a as s,u as t};
1
+ import{_ as e}from"./vendor.js";import{l as t}from"./core.js";import{i}from"./scanner.js";class n{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(),t.info("[SecurityManager] Initialized with config:",this.config)}static getInstance(e){return n.instance||(n.instance=new n(e)),n.instance}validateTextFieldUpdate(e,t,i,n){const s=`${e}:${t}`;if(this.blockedInstances.has(e))return{allowed:!1,reason:"Instance blocked due to security violations",severity:"high"};if(i.length>this.config.maxTextLength)return this.recordViolation(e,"text_length_exceeded"),{allowed:!1,reason:`Text length exceeds maximum (${this.config.maxTextLength} characters)`,severity:"medium"};if(this.config.enableRateLimit){const t=this.checkRateLimit(s);if(!t.allowed)return this.recordViolation(e,"rate_limit_exceeded"),t}if(this.config.enableBotDetection){const t=this.analyzeBehavior(e,i);if(!t.allowed)return this.recordViolation(e,"suspicious_behavior"),t}let a=i;if(this.config.enableSanitization){const t=this.sanitizeInput(i);if(!t.allowed)return this.recordViolation(e,"malicious_content"),t;a=t.sanitizedText||i}const r=this.analyzeContentPatterns(i);return r.allowed?{allowed:!0,sanitizedText:a}:(this.recordViolation(e,"suspicious_pattern"),r)}sanitizeInput(e){try{const t=/javascript:/gi,i=/\bon\w+\s*=/gi,n=/data:text\/html/gi;if(/<script[^>]*>[\s\S]*?<\/script>/gi.test(e)||t.test(e)||i.test(e)||n.test(e))return{allowed:!1,reason:"Potentially malicious content detected",severity:"high"};let s=e.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/javascript:/gi,"").replace(/\bon\w+\s*=/gi,"").replace(/data:text\/html/gi,"data:text/plain");s=this.sanitizeLinks(s);const a=(s.match(/<[a-z][^>]*>/gi)||[]).length,r=s.replace(/<[^>]+>/g,"").length;if(a>0&&r>0){if(a/r>.1)return{allowed:!1,reason:"Excessive HTML content detected",severity:"medium"}}return{allowed:!0,sanitizedText:s}}catch(e){return t.warn("[SecurityManager] Sanitization error:",e),{allowed:!1,reason:"Input sanitization failed",severity:"medium"}}}sanitizeLinks(e){try{const t=/<a\b(?![^>]*\bhref\s*=)[^>]*>/gi,i=e.replace(/<a\b(?![^>]*\bhref\s*=)[^>]*>([\s\S]*?)<\/a>/gi,"$1").replace(t,""),n=/<a\s+([^>]*href\s*=\s*["'][^"']*["'][^>]*)>/gi;return i.replace(n,((e,t)=>{const i=t.match(/href\s*=\s*["']([^"']*)["']/i);if(!i)return"";const n=i[1],s=["javascript:","data:","vbscript:","file:","ftp:"];for(const e of s)if(n.toLowerCase().startsWith(e))return"";const a=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+=a?' target="_blank" rel="nofollow noopener noreferrer"':' rel="noopener"',`<a ${r}>`}))}catch(i){return t.warn("[SecurityManager] Link sanitization error:",i),e}}isExternalLink(e){try{if(e.startsWith("//"))return!0;if(e.startsWith("/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("#")||e.startsWith("?"))return!1;if(e.includes("://")){const t=new URL(e),i="undefined"!=typeof window?window.location.hostname:"";return t.hostname!==i}return!1}catch(e){return!0}}checkRateLimit(e){const t=Date.now(),i=this.rateLimitTracker.get(e)||{count:0,windowStart:t,violations:0};return t-i.windowStart>=6e4&&(i.count=0,i.windowStart=t),i.count++,this.rateLimitTracker.set(e,i),i.count>this.config.maxUpdatesPerMinute?(i.violations++,{allowed:!1,reason:"Rate limit exceeded for this widget",severity:"medium"}):(t-this.globalRateLimit.windowStart>=6e4&&(this.globalRateLimit.count=0,this.globalRateLimit.windowStart=t),this.globalRateLimit.count++,this.globalRateLimit.count>this.config.maxGlobalUpdatesPerMinute?(this.globalRateLimit.violations++,{allowed:!1,reason:"Global rate limit exceeded",severity:"high"}):{allowed:!0})}analyzeBehavior(e,t){const i=Date.now(),n=this.behaviorTracker.get(e)||{updateCount:0,averageInterval:0,suspiciousPatterns:0,firstSeen:i,lastSeen:i,textLengthVariations:[],updateIntervals:[]},s=i-n.lastSeen;if(n.updateIntervals.push(s),n.textLengthVariations.push(t.length),n.updateIntervals.length>20&&(n.updateIntervals=n.updateIntervals.slice(-20),n.textLengthVariations=n.textLengthVariations.slice(-20)),n.updateCount++,n.lastSeen=i,n.updateIntervals.length>1){const e=n.updateIntervals.filter((e=>e>0));n.averageInterval=e.reduce(((e,t)=>e+t),0)/e.length}let a=0;if(n.updateIntervals.length>=5){const e=n.updateIntervals.slice(-5);this.calculateVariance(e)<100&&a++}if(n.updateIntervals.length>=3){n.updateIntervals.slice(-3).every((e=>e<100&&e>0))&&a++}if(n.textLengthVariations.length>=5){const e=n.textLengthVariations.slice(-5);1===new Set(e).size&&e[0]>10&&a++}const r=i-n.firstSeen;if(r>0&&n.updateCount>50){n.updateCount/(r/1e3)>2&&a++}if(n.suspiciousPatterns=a,this.behaviorTracker.set(e,n),a>=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,i){t.warn(`[SecurityManager] Security violation: ${i}`,{instanceId:e});const n=`${e}:violations`,s=this.rateLimitTracker.get(n)||{count:0,windowStart:Date.now(),violations:0};s.violations++,this.rateLimitTracker.set(n,s),s.violations>=10&&(this.blockedInstances.add(e),t.warn(`[SecurityManager] Blocked instance due to repeated violations: ${e}`)),"undefined"!=typeof document&&document.dispatchEvent(new CustomEvent("widgetic:security-violation",{detail:{instanceId:e,violationType:i,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(),i=18e5;for(const[t,n]of this.rateLimitTracker.entries())e-n.windowStart>i&&this.rateLimitTracker.delete(t);for(const[t,n]of this.behaviorTracker.entries())e-n.lastSeen>i&&this.behaviorTracker.delete(t);t.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);t.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),t.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(),t.info("[SecurityManager] Destroyed")}}function s(e){return n.getInstance(e)}var a=Object.freeze({__proto__:null,SecurityManager:n,getSecurityManager:s});class r{constructor(e={}){var i,s,a,r;this.cspDirectives=new Map,this.cspNonce="",this.encryptionKey=null,this.sensitiveDataCache=new Map,this.contentFilters=new Map,this.moderationQueue=new Map,this.auditEvents=[],this.auditBuffer=new Map,this.threatPatterns=new Map,this.threatScores=new Map,this.consentStatus=new Map,this.dataSubjects=new Map,this.config=Object.assign({enableSanitization:!0,enableRateLimit:!0,enableBotDetection:!0,maxTextLength:1e5,maxUpdatesPerMinute:60,maxGlobalUpdatesPerMinute:1e3,suspiciousActivityThreshold:5,auditLogging:!0,threatDetection:!0,csp:{level:"balanced",allowInlineStyles:!1,allowEval:!1,reportOnly:!1},secureData:{classification:"internal",encryptInTransit:!0,encryptAtRest:!1,anonymizeData:!1,dataRetentionDays:90},contentFilter:{enableProfanityFilter:!0,enableSpamDetection:!0,enableMalwareScanning:!0,autoModeration:!1},privacy:{enableGDPRCompliance:!0,enableCCPACompliance:!0,anonymizeUserData:!1,cookieConsent:!0,dataProcessingBasis:"legitimate_interest",dataSubjectRights:!0}},e),this.baseSecurityManager=n.getInstance(this.config),this.initializeCSP(),this.initializeDataSecurity(),this.initializeContentFilters(),this.initializeThreatDetection(),this.initializePrivacyControls(),t.info("[AdvancedSecurityManager] Initialized with config:",{cspLevel:null===(i=this.config.csp)||void 0===i?void 0:i.level,dataClassification:null===(s=this.config.secureData)||void 0===s?void 0:s.classification,contentFiltering:null===(a=this.config.contentFilter)||void 0===a?void 0:a.enableProfanityFilter,privacy:null===(r=this.config.privacy)||void 0===r?void 0:r.enableGDPRCompliance})}static getInstance(e){return r.instance||(r.instance=new r(e)),r.instance}initializeCSP(){this.config.csp&&(this.cspNonce=this.generateNonce(),this.setupCSPDirectives(),this.applyCSP(),t.info("[AdvancedSecurityManager] CSP initialized with level:",this.config.csp.level))}generateNonce(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}setupCSPDirectives(){var e,t;const{level:i,allowedDomains:n=[],allowInlineStyles:s,allowEval:a}=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,...a?["'unsafe-eval'"]:[]]),this.cspDirectives.set("style-src",["'self'",`'nonce-${this.cspNonce}'`,...r,...s?["'unsafe-inline'"]:[]]),this.cspDirectives.set("img-src",["'self'","data:","blob:","https:",...r]),this.cspDirectives.set("connect-src",["'self'",...r]),this.cspDirectives.set("font-src",["'self'","https:",...r]),this.cspDirectives.set("media-src",["'self'","blob:","https:",...r]),this.cspDirectives.set("object-src",["'none'"]),this.cspDirectives.set("base-uri",["'self'"]),this.cspDirectives.set("form-action",["'self'",...r]),this.cspDirectives.set("frame-ancestors",["'self'",...r]);break;case"permissive":this.cspDirectives.set("default-src",["'self'",...r,"https:"]),this.cspDirectives.set("script-src",["'self'","'unsafe-inline'","'unsafe-eval'",...r,"https:"]),this.cspDirectives.set("style-src",["'self'","'unsafe-inline'",...r,"https:"]),this.cspDirectives.set("img-src",["*","data:","blob:"]),this.cspDirectives.set("connect-src",["*"]),this.cspDirectives.set("font-src",["*"]),this.cspDirectives.set("media-src",["*"]),this.cspDirectives.set("object-src",["'none'"]),this.cspDirectives.set("base-uri",["'self'"]),this.cspDirectives.set("form-action",["*"])}(null===(e=this.config.csp)||void 0===e?void 0:e.customDirectives)&&Object.entries(this.config.csp.customDirectives).forEach((([e,t])=>{this.cspDirectives.set(e,t)})),(null===(t=this.config.csp)||void 0===t?void 0:t.reportUri)&&this.cspDirectives.set("report-uri",[this.config.csp.reportUri])}applyCSP(){var e;if("undefined"==typeof document)return;const i=this.buildCSPString();let n=document.querySelector('meta[http-equiv="Content-Security-Policy"]');n||(n=document.createElement("meta"),n.httpEquiv="Content-Security-Policy",document.head.appendChild(n)),(null===(e=this.config.csp)||void 0===e?void 0:e.reportOnly)&&(n.httpEquiv="Content-Security-Policy-Report-Only"),n.content=i,t.info("[AdvancedSecurityManager] CSP applied:",i)}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 e(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"]),t.info("[AdvancedSecurityManager] Data encryption initialized")}catch(e){t.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)})),t.info("[AdvancedSecurityManager] Content filtering initialized with filters:",Array.from(this.contentFilters.keys())))}addDefaultContentFilters(){var t,i,n;(null===(t=this.config.contentFilter)||void 0===t?void 0:t.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:(t,i)=>e(this,void 0,void 0,(function*(){return this.detectLinkSpam(t)}))})),(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)})),t.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(),t.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){t.warn("[AdvancedSecurityManager] Failed to parse existing consent:",e)}}}initializeDataSubjectRights(){t.info("[AdvancedSecurityManager] Data subject rights initialized")}validateContent(i,n){return e(this,arguments,void 0,(function*(e,i,n={}){var s;const a=[];let r=i;try{const t=this.baseSecurityManager.validateTextFieldUpdate(e,n.fieldId||"content",i,n);if(!t.allowed)return a.push({filterId:"basic_security",filterName:"Basic Security",severity:t.severity||"medium",reason:t.reason||"Basic security validation failed"}),yield this.logAuditEvent({type:"security_violation",widgetId:e,action:"content_validation",outcome:"blocked",details:{reason:t.reason,contentLength:i.length},classification:"internal",severity:"medium",userId:n.userId,sessionId:n.sessionId}),{allowed:!1,violations:a};if(t.sanitizedText&&(r=t.sanitizedText),this.config.threatDetection){const t=yield this.detectThreats(e,r,n);if(t.violations.length>0){if(a.push(...t.violations),!t.allowed)return{allowed:!1,violations:a};t.filteredContent&&(r=t.filteredContent)}}if(this.config.contentFilter){const t=yield this.applyContentFilters(r,n);if(t.violations.length>0){if(a.push(...t.violations),!t.allowed)return yield this.logAuditEvent({type:"content_filtered",widgetId:e,action:"content_blocked",outcome:"blocked",details:{violations:t.violations,originalLength:i.length},classification:"internal",severity:"medium",userId:n.userId,sessionId:n.sessionId}),{allowed:!1,violations:a};t.filteredContent&&(r=t.filteredContent)}}return 0===a.length&&(yield this.logAuditEvent({type:"data_accessed",widgetId:e,action:"content_validated",outcome:"success",details:{contentLength:i.length,filtered:r!==i},classification:(null===(s=this.config.secureData)||void 0===s?void 0:s.classification)||"internal",severity:"low",userId:n.userId,sessionId:n.sessionId})),{allowed:!0,filteredContent:r!==i?r:void 0,violations:a}}catch(i){return t.error("[AdvancedSecurityManager] Content validation error:",i),yield this.logAuditEvent({type:"security_violation",widgetId:e,action:"content_validation_error",outcome:"failure",details:{error:i instanceof Error?i.message:"Unknown error"},classification:"internal",severity:"high",userId:n.userId,sessionId:n.sessionId}),a.push({filterId:"system_error",filterName:"System Error",severity:"critical",reason:"Content validation system error"}),{allowed:!1,violations:a}}}))}applyContentFilters(i,n){return e(this,void 0,void 0,(function*(){const e=[];let s=i,a=!1;for(const[i,r]of this.contentFilters)try{const t=yield this.applyFilter(r,s,n);if(t.violations&&e.push(...t.violations),!t.allowed){if("block"===r.action){a=!0;break}"moderate"===r.action&&this.moderationQueue.set(`${Date.now()}-${i}`,{content:s,filter:r,context:n,timestamp:Date.now()})}t.filteredContent&&(s=t.filteredContent)}catch(n){t.error(`[AdvancedSecurityManager] Filter ${i} error:`,n),e.push({filterId:i,filterName:r.name,severity:"medium",reason:"Filter processing error"})}return{allowed:!a,filteredContent:s!==i?s:void 0,violations:e}}))}applyFilter(t,i,n){return e(this,void 0,void 0,(function*(){switch(t.type){case"regex":return this.applyRegexFilter(t,i);case"keyword":return this.applyKeywordFilter(t,i);case"custom":return t.customHandler?yield t.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 s=n.map((t=>({filterId:e.id,filterName:e.name,severity:e.severity,reason:`Pattern matched: ${t}`}))),a=t.replace(i,"[FILTERED]");return{allowed:"block"!==e.action,filtered:!0,filteredContent:a,violations:s,confidence:.9}}return{allowed:!0}}applyKeywordFilter(e,t){if(!e.keywords||0===e.keywords.length)return{allowed:!0};const i=t.toLowerCase(),n=[];let s=t;for(const t of e.keywords){const a=t.toLowerCase();if(i.includes(a)){n.push({filterId:e.id,filterName:e.name,severity:e.severity,reason:`Keyword detected: ${t}`});const i=new RegExp(t,"gi");s=s.replace(i,"[FILTERED]")}}return n.length>0?{allowed:"block"!==e.action,filtered:!0,filteredContent:s,violations:n,confidence:.8}:{allowed:!0}}detectLinkSpam(i){return e(this,void 0,void 0,(function*(){const e=[];let n=0;try{const t=/<a[^>]*href\s*=\s*["']([^"']*)["'][^>]*>([^<]*)<\/a>/gi,s=[];let a;for(;null!==(a=t.exec(i));)s.push({url:a[1],text:a[2],match:a[0]});s.length>5&&(n+=3,e.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"medium",reason:`Excessive number of links detected: ${s.length}`}));for(const t of s){["bit.ly","tinyurl","t.co","goo.gl","ow.ly","tiny.cc"].some((e=>t.url.includes(e)))&&(n+=2,e.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"medium",reason:`URL shortener detected: ${t.url}`}));["click here","read more","visit now","buy now","order now","download now","get started","try free","join now","sign up"].some((e=>t.text.toLowerCase().includes(e.toLowerCase())))&&(n+=1,e.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"low",reason:`Suspicious link text: "${t.text}"`}));[".tk",".ml",".ga",".cf",".buzz",".click"].some((e=>t.url.includes(e)))&&(n+=2,e.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"medium",reason:`Suspicious domain: ${t.url}`})),t.text.includes("http")&&!t.url.includes(t.text.replace(/^https?:\/\//,""))&&(n+=3,e.push({filterId:"link_spam",filterName:"Link Spam Detection",severity:"high",reason:`Mismatched link text and URL: "${t.text}" -> ${t.url}`}))}const r=n>=5,o=Math.min(n/10,1);return{allowed:!r,filtered:e.length>0,violations:e,confidence:o,requiresModeration:n>=3&&n<5}}catch(e){return t.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(t,i,n){return e(this,void 0,void 0,(function*(){const e=[];let s=0,a=!1;for(const[r,o]of this.threatPatterns){let c=0;for(const e of o.indicators){c+=this.evaluateIndicator(e,i,n)}const l=Math.min(10,c);s+=l,l>=7&&(e.push({filterId:r,filterName:o.name,severity:o.severity,reason:o.description}),"block"!==o.responseAction&&"quarantine"!==o.responseAction||(a=!0),yield this.logAuditEvent({type:"threat_detected",widgetId:t,action:"threat_pattern_matched",outcome:a?"blocked":"suspicious",details:{patternId:r,patternName:o.name,threatScore:l,indicators:o.indicators.length},classification:"confidential",severity:o.severity,userId:n.userId,sessionId:n.sessionId}))}const r=`${t}:${n.userId||"anonymous"}`;return this.threatScores.set(r,(this.threatScores.get(r)||0)+s),{allowed:!a,violations:e}}))}evaluateIndicator(e,i,n){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(i)?e.weight:0}break;case"content":if("function"==typeof e.condition)return e.condition(i)?e.weight:0;break;case"behavior":case"frequency":if("function"==typeof e.condition)return e.condition(n)?e.weight:0}return 0}catch(e){return t.warn("[AdvancedSecurityManager] Indicator evaluation error:",e),0}}logAuditEvent(i){return e(this,void 0,void 0,(function*(){if(!this.config.auditLogging)return;const e=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:{}},i),n=e.widgetId;this.auditBuffer.has(n)||this.auditBuffer.set(n,[]),this.auditBuffer.get(n).push(e),this.auditEvents.push(e),this.auditEvents.length>1e3&&this.auditEvents.splice(0,this.auditEvents.length-1e3);const s=this.getLogLevel(e.severity);t[s](`[SecurityAudit] ${e.type}:`,{id:e.id,widgetId:e.widgetId,action:e.action,outcome:e.outcome,severity:e.severity,userId:e.userId}),"undefined"!=typeof document&&document.dispatchEvent(new CustomEvent("widgetic:security-audit",{detail:e}))}))}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,i,n,s={}){if(this.consentStatus.set(i,n),"undefined"!=typeof localStorage){const e=JSON.parse(localStorage.getItem("widgetic_privacy_consent")||"{}");e[i]=n,e.timestamp=Date.now(),localStorage.setItem("widgetic_privacy_consent",JSON.stringify(e))}this.logAuditEvent({type:"privacy_consent",widgetId:e,action:"consent_"+(n?"granted":"revoked"),outcome:"success",details:{consentType:i,granted:n},classification:"confidential",severity:"medium",userId:s.userId,sessionId:s.sessionId}),t.info(`[AdvancedSecurityManager] Privacy consent ${n?"granted":"revoked"}:`,{consentType:i,widgetId:e,userId:s.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"}}}function o(e){return r.getInstance(e)}var c=Object.freeze({__proto__:null,AdvancedSecurityManager:r,getAdvancedSecurityManager:o});class l{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=s(),this.initialize()}static getInstance(){return l.instance||(l.instance=new l),l.instance}initialize(){this.initialized||(i()?(this.loadStoredState(),this.cleanupOldEntries(),this.initialized=!0,t.info("[TextFieldManager] Initialized successfully")):t.warn("[TextFieldManager] localStorage not available, text persistence disabled"))}registerTextField(e,i,n={}){const s=this.generateStateKey(e,i);t.debug(`[TextFieldManager] Registering text field: ${e}.${i}`,{config:n});const a=this.textStates.get(s);return a&&n.autoRestore&&this.shouldAutoRestore(a,n)&&t.debug(`[TextFieldManager] Auto-restoring text for ${s}`,{textLength:a.text.length,lastModified:new Date(a.lastModified)}),s}updateTextField(e,i,n,s={},a){const r=this.securityManager.validateTextFieldUpdate(e,i,n,a);if(!r.allowed)return t.warn(`[TextFieldManager] Security validation failed for ${e}.${i}`,{reason:r.reason,severity:r.severity}),void("undefined"!=typeof document&&document.dispatchEvent(new CustomEvent("widgetic:text-field-security-blocked",{detail:{instanceId:e,fieldId:i,reason:r.reason,severity:r.severity,originalTextLength:n.length,timestamp:Date.now()}})));const o=r.sanitizedText||n,c=this.generateStateKey(e,i);let l=o;s.maxLength&&o.length>s.maxLength&&(t.warn(`[TextFieldManager] Text exceeds maxLength (${s.maxLength}), truncating`),l=o.substring(0,s.maxLength));const d={instanceId:e,fieldId:i,text:l,lastModified:Date.now(),textType:s.textType||"custom",metadata:Object.assign(Object.assign({},a),{characterCount:l.length,wordCount:this.countWords(l),sanitized:o!==n})};this.textStates.set(c,d),s.autoPersist&&s.persistState&&this.debouncePersist(c,s.debounceDelay||1e3),t.debug(`[TextFieldManager] Updated text field: ${c}`,{textLength:l.length,textType:d.textType,sanitized:o!==n})}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,i){const n=this.generateStateKey(e,i);this.textStates.delete(n),this.clearDebounceTimer(n),this.persistState(),t.debug(`[TextFieldManager] Cleared text field: ${n}`)}clearWidgetTextFields(e){const i=[];for(const[t,n]of this.textStates)n.instanceId===e&&i.push(t);i.forEach((e=>{this.textStates.delete(e),this.clearDebounceTimer(e)})),this.persistState(),t.debug(`[TextFieldManager] Cleared ${i.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 i=JSON.parse(e);if(i.version!==this.storageVersion)return t.info("[TextFieldManager] Storage version mismatch, clearing stored data"),void localStorage.removeItem(this.storageKey);i.textStates&&(this.textStates=new Map(Object.entries(i.textStates)),t.debug(`[TextFieldManager] Loaded ${this.textStates.size} text field states from storage`)),"boolean"==typeof i.autoRestoreEnabled&&(this.autoRestoreEnabled=i.autoRestoreEnabled)}catch(e){t.warn("[TextFieldManager] Failed to load stored state:",e),localStorage.removeItem(this.storageKey)}}persistState(){if(i())try{const e={version:this.storageVersion,textStates:Object.fromEntries(this.textStates),timestamp:Date.now(),autoRestoreEnabled:this.autoRestoreEnabled};localStorage.setItem(this.storageKey,JSON.stringify(e)),t.debug(`[TextFieldManager] Persisted state for ${this.textStates.size} text fields`)}catch(e){t.warn("[TextFieldManager] Failed to persist state:",e)}}cleanupOldEntries(){const e=Date.now()-this.maxStorageAge,i=[];for(const[t,n]of this.textStates)n.lastModified<e&&i.push(t);i.length>0&&(i.forEach((e=>this.textStates.delete(e))),this.persistState(),t.debug(`[TextFieldManager] Cleaned up ${i.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(),t.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(),i()&&localStorage.removeItem(this.storageKey),t.debug("[TextFieldManager] Cleaned up all data")}configureSecurity(e){this.securityManager.updateConfig(e),t.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),t.info(`[TextFieldManager] Unblocked instance: ${e}`)}getSecurityStats(){return this.securityManager.getSecurityStats()}validateText(e,t,i,n){return this.securityManager.validateTextFieldUpdate(e,t,i,n)}}function d(){return l.getInstance()}var u=Object.freeze({__proto__:null,TextFieldManager:l,getTextField:function(e,t){return d().getTextField(e,t)},getTextFieldManager:d,registerTextField:function(e,t,i){return d().registerTextField(e,t,i)},updateTextField:function(e,t,i,n,s){d().updateTextField(e,t,i,n,s)}});export{n as S,c as a,o as g,a as s,u as t};
@@ -1 +1 @@
1
- import{_ as t}from"./chunks/vendor.js";import{l as e,h as i,a as n}from"./chunks/core.js";import"./chunks/api.js";import"./chunks/renderers.js";import"./chunks/scanner.js";import"./chunks/media.js";import"./chunks/messaging.js";import"./chunks/display.js";import"./chunks/advanced.js";import"./chunks/security.js";import"./chunks/performance.js";class s{constructor(){this.foundWidgets=[],this.scanStartTime=0}scan(){this.scanStartTime=performance.now();const t=["[data-composition-id]","[data-widget-id]","widgetic-widget","widgetic"],i=[];for(const e of t){const t=document.querySelectorAll(e);for(const e of Array.from(t))this.isValidWidget(e)&&i.push(e)}this.foundWidgets=i;const n=performance.now()-this.scanStartTime;return e.info(`FastScanner: Found ${i.length} widgets in ${n.toFixed(2)}ms`),i}isValidWidget(t){return t.hasAttribute("data-composition-id")||t.hasAttribute("data-widget-id")||t.hasAttribute("composition-id")}getScanTime(){return this.scanStartTime>0?performance.now()-this.scanStartTime:0}}class a{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 t=[this.loadChunk("core",(()=>import("./chunks/core.js").then((function(t){return t.o})))),this.loadChunk("scanner",(()=>import("./chunks/scanner.js").then((function(t){return t.l})))),this.loadChunk("scanner",(()=>import("./chunks/scanner.js").then((function(t){return t.n}))))];yield Promise.all(t),e.debug("ProgressiveLoader: Core chunks loaded")}))}loadRenderingChunks(){return t(this,void 0,void 0,(function*(){const t=[this.loadChunk("renderers",(()=>import("./chunks/renderers.js").then((function(t){return t.w})))),this.loadChunk("renderers",(()=>import("./chunks/renderers.js").then((function(t){return t.c})))),this.loadChunk("renderers",(()=>import("./chunks/renderers.js").then((function(t){return t.i}))))];yield Promise.all(t),e.debug("ProgressiveLoader: Rendering chunks loaded")}))}loadApiChunks(){return t(this,void 0,void 0,(function*(){const t=[this.loadChunk("api",(()=>import("./chunks/api.js").then((function(t){return t.z})))),this.loadChunk("api",(()=>import("./chunks/api.js").then((function(t){return t.G}))))];yield Promise.all(t),e.debug("ProgressiveLoader: API chunks loaded")}))}loadFeatureChunk(i){return t(this,void 0,void 0,(function*(){switch(i){case"messaging":return this.loadChunk("messaging",(()=>import("./chunks/messaging.js")));case"media":return this.loadChunk("media",(()=>import("./chunks/media.js").then((function(t){return t.m}))));case"performance":return this.loadChunk("performance",(()=>import("./chunks/performance.js").then((function(t){return t.p}))));case"advanced":return this.loadChunk("advanced",(()=>import("./chunks/advanced.js").then((function(t){return t.i}))));case"security":return this.loadChunk("security",(()=>import("./chunks/security.js").then((function(t){return t.a}))));case"display":return this.loadChunk("display",(()=>import("./chunks/display.js").then((function(t){return t.d}))));case"abTesting":return this.loadChunk("abTesting",(()=>import("./chunks/ABTestManager.js")));default:return e.warn(`ProgressiveLoader: Unknown feature '${i}'`),null}}))}loadChunk(i,n){return t(this,void 0,void 0,(function*(){if(this.loadedChunks.has(i))return;if(this.loadingPromises.has(i))return this.loadingPromises.get(i);const t=n().then((t=>(this.loadedChunks.add(i),e.debug(`ProgressiveLoader: Loaded chunk '${i}'`),t))).catch((t=>{throw e.error(`ProgressiveLoader: Failed to load chunk '${i}'`,t),t}));return this.loadingPromises.set(i,t),t}))}getLoadedChunks(){return Array.from(this.loadedChunks)}getTotalLoadTime(){return performance.now()-this.loadStartTime}}class r{constructor(t={}){this.scanner=new s,this.loader=new a,this.config=Object.assign({debug:!1,preloadCritical:!0,scanInterval:0,enableLazyLoading:!0},t),this.initStartTime=performance.now(),this.stats={scanTime:0,widgetsFound:0,chunksLoaded:[],totalLoadTime:0},this.config.debug&&(i.setDebug(!0),i.setLevel("debug"))}initialize(){return t(this,void 0,void 0,(function*(){try{e.info("WidgeticBootstrap: Starting fast initialization...");const t=this.scanner.scan();if(this.stats.widgetsFound=t.length,this.stats.scanTime=this.scanner.getScanTime(),0===t.length)return e.info("WidgeticBootstrap: No widgets found, minimal initialization"),this.finalizeStats(),this.stats;this.config.preloadCritical&&(yield this.loader.loadCoreChunks());const i=this.analyzeWidgetRequirements(t);let n=[];try{const{analyzeWidgetRequirementsEnhanced:e}=yield import("./chunks/scanner.js").then((function(t){return t.w}));n=e(t)}catch(t){}const s=[...new Set([...i,...n])];return yield this.loadRequiredChunks(s),yield this.initializeFullSDK(t),this.finalizeStats(),e.info(`WidgeticBootstrap: Initialization complete in ${this.stats.totalLoadTime.toFixed(2)}ms`),this.stats}catch(t){throw e.error("WidgeticBootstrap: Initialization failed",t),t}}))}analyzeWidgetRequirements(t){const i=new Set;i.add("rendering"),i.add("api");for(const e of t){("widgetic-abtest"===e.tagName.toLowerCase()||e.hasAttribute("experiment-id")||e.hasAttribute("data-ab-test"))&&(i.add("abTesting"),i.add("messaging")),e.hasAttribute("data-interactive")&&i.add("messaging");const t=this.extractWidgetCapabilities(e);t.length>0&&t.forEach((t=>i.add(t)));const n=e.getAttribute("data-widget-id")||"",s=e.getAttribute("data-widget-type")||"";(n.includes("video")||n.includes("audio")||n.includes("media")||"media"===s)&&i.add("media"),(e.hasAttribute("data-editing")||"editing"===e.getAttribute("data-render-mode"))&&i.add("advanced");const a=e.getAttribute("data-display-mode");"overlay"!==a&&"popup"!==a&&"fullscreen"!==a||i.add("display"),(n.includes("form")||n.includes("input")||n.includes("contact")||"form"===s)&&i.add("security"),"gallery"!==s&&"interactive"!==s||i.add("messaging")}return e.debug("WidgeticBootstrap: Required features:",Array.from(i)),Array.from(i)}extractWidgetCapabilities(t){var i;const n=[];try{const e=t.getAttribute("data-widget-meta");if(e){const t=JSON.parse(e);(t.mediaCapabilities||t.supportsMedia)&&n.push("media"),(t.textCapabilities||t.supportsText||t.hasTextFields)&&n.push("security"),(t.supportsInteraction||t.hasInteractiveElements)&&n.push("messaging"),(t.supportsFullscreen||t.supportsOverlay)&&n.push("display"),(t.supportsABTesting||t.trackingCapabilities)&&n.push("abTesting")}const s=t.getAttribute("data-widget-type");if(s)switch(s){case"media":n.push("media");break;case"form":n.push("security","messaging");break;case"gallery":case"interactive":n.push("messaging")}if(t.matches("widgetic-widget[data-capabilities]")){const e=(null===(i=t.getAttribute("data-capabilities"))||void 0===i?void 0:i.split(","))||[];n.push(...e.map((t=>t.trim())))}}catch(t){e.debug("Failed to parse widget metadata, using fallback detection",{error:t})}return n}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(i){return t(this,void 0,void 0,(function*(){var t;const{getSDK:n}=yield import("./chunks/api.js").then((function(t){return t.I})),s=n({debug:this.config.debug,lazyLoading:{enabled:null===(t=this.config.enableLazyLoading)||void 0===t||t,config:{}}});yield s.init(),e.info(`WidgeticBootstrap: Processing ${i.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 o=null;function d(i){return t(this,void 0,void 0,(function*(){return o?(e.warn("WidgeticBootstrap: Already initialized"),o.getStats()):(o=new r(i),yield o.initialize())}))}function u(){return(null==o?void 0:o.getStats())||null}if("undefined"!=typeof document){const t=()=>{window.__WIDGETIC_SDK_INITIALIZED__||d({debug:"development"===n.NODE_ENV,preloadCritical:!0}).catch((t=>{e.error("WidgeticBootstrap: Auto-initialization failed",t)}))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):setTimeout(t,0)}"undefined"!=typeof window&&(window.WidgeticBootstrap={init:d,getStats:u,version:"1.0.0"});export{r as BootstrapManager,s as FastWidgetScanner,a as ProgressiveChunkLoader,u as getBootstrapStats,d as initializeWidgeticFast};
1
+ import{_ as t}from"./chunks/vendor.js";import{l as e,e as i,d as n}from"./chunks/core.js";class s{constructor(){this.foundWidgets=[],this.scanStartTime=0}scan(){this.scanStartTime=performance.now();const t=["[data-composition-id]","[data-widget-id]","widgetic-widget","widgetic"],i=[];for(const e of t){const t=document.querySelectorAll(e);for(const e of Array.from(t))this.isValidWidget(e)&&i.push(e)}this.foundWidgets=i;const n=performance.now()-this.scanStartTime;return e.info(`FastScanner: Found ${i.length} widgets in ${n.toFixed(2)}ms`),i}isValidWidget(t){return t.hasAttribute("data-composition-id")||t.hasAttribute("data-widget-id")||t.hasAttribute("composition-id")}getScanTime(){return this.scanStartTime>0?performance.now()-this.scanStartTime:0}}class a{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 t=[this.loadChunk("core",(()=>import("./chunks/core.js").then((function(t){return t.v})))),this.loadChunk("scanner",(()=>import("./chunks/scanner.js").then((function(t){return t.n})))),this.loadChunk("scanner",(()=>import("./chunks/scanner.js").then((function(t){return t.q}))))];yield Promise.all(t),e.debug("ProgressiveLoader: Core chunks loaded")}))}loadRenderingChunks(){return t(this,void 0,void 0,(function*(){const t=[this.loadChunk("renderers",(()=>import("./chunks/renderers.js").then((function(t){return t.w})))),this.loadChunk("renderers",(()=>import("./chunks/renderers.js").then((function(t){return t.i})))),this.loadChunk("renderers",(()=>import("./chunks/renderers.js").then((function(t){return t.j}))))];yield Promise.all(t),e.debug("ProgressiveLoader: Rendering chunks loaded")}))}loadApiChunks(){return t(this,void 0,void 0,(function*(){const t=[this.loadChunk("api",(()=>import("./chunks/api.js").then((function(t){return t.n})))),this.loadChunk("api",(()=>import("./chunks/api.js").then((function(t){return t.o}))))];yield Promise.all(t),e.debug("ProgressiveLoader: API chunks loaded")}))}loadFeatureChunk(i){return t(this,void 0,void 0,(function*(){switch(i){case"messaging":return this.loadChunk("messaging",(()=>import("./chunks/messaging.js")));case"media":return this.loadChunk("media",(()=>import("./chunks/media.js").then((function(t){return t.m}))));case"performance":return this.loadChunk("performance",(()=>import("./chunks/performance.js").then((function(t){return t.p}))));case"advanced":return this.loadChunk("advanced",(()=>import("./chunks/advanced.js").then((function(t){return t.e}))));case"security":return this.loadChunk("security",(()=>import("./chunks/security.js").then((function(t){return t.a}))));case"display":return this.loadChunk("display",(()=>import("./chunks/display.js").then((function(t){return t.d}))));case"abTesting":return this.loadChunk("abTesting",(()=>import("./chunks/ABTestManager.js").then((function(t){return t.a}))));default:return e.warn(`ProgressiveLoader: Unknown feature '${i}'`),null}}))}loadChunk(i,n){return t(this,void 0,void 0,(function*(){if(this.loadedChunks.has(i))return;if(this.loadingPromises.has(i))return this.loadingPromises.get(i);const t=n().then((t=>(this.loadedChunks.add(i),e.debug(`ProgressiveLoader: Loaded chunk '${i}'`),t))).catch((t=>{throw e.error(`ProgressiveLoader: Failed to load chunk '${i}'`,t),t}));return this.loadingPromises.set(i,t),t}))}getLoadedChunks(){return Array.from(this.loadedChunks)}getTotalLoadTime(){return performance.now()-this.loadStartTime}}class r{constructor(t={}){this.scanner=new s,this.loader=new a,this.config=Object.assign({debug:!1,preloadCritical:!0,scanInterval:0,enableLazyLoading:!0},t),this.initStartTime=performance.now(),this.stats={scanTime:0,widgetsFound:0,chunksLoaded:[],totalLoadTime:0},this.config.debug&&(i.setDebug(!0),i.setLevel("debug"))}initialize(){return t(this,void 0,void 0,(function*(){try{e.info("WidgeticBootstrap: Starting fast initialization...");const t=this.scanner.scan();if(this.stats.widgetsFound=t.length,this.stats.scanTime=this.scanner.getScanTime(),0===t.length)return e.info("WidgeticBootstrap: No widgets found, minimal initialization"),this.finalizeStats(),this.stats;this.config.preloadCritical&&(yield this.loader.loadCoreChunks());const i=this.analyzeWidgetRequirements(t);let n=[];try{const{analyzeWidgetRequirementsEnhanced:e}=yield import("./chunks/scanner.js").then((function(t){return t.w}));n=e(t)}catch(t){}const s=[...new Set([...i,...n])];return yield this.loadRequiredChunks(s),yield this.initializeFullSDK(t),this.finalizeStats(),e.info(`WidgeticBootstrap: Initialization complete in ${this.stats.totalLoadTime.toFixed(2)}ms`),this.stats}catch(t){throw e.error("WidgeticBootstrap: Initialization failed",t),t}}))}analyzeWidgetRequirements(t){const i=new Set;i.add("rendering"),i.add("api");for(const e of t){("widgetic-abtest"===e.tagName.toLowerCase()||e.hasAttribute("experiment-id")||e.hasAttribute("data-ab-test"))&&(i.add("abTesting"),i.add("messaging")),e.hasAttribute("data-interactive")&&i.add("messaging");const t=this.extractWidgetCapabilities(e);t.length>0&&t.forEach((t=>i.add(t)));const n=e.getAttribute("data-widget-id")||"",s=e.getAttribute("data-widget-type")||"";(n.includes("video")||n.includes("audio")||n.includes("media")||"media"===s)&&i.add("media"),(e.hasAttribute("data-editing")||"editing"===e.getAttribute("data-render-mode"))&&i.add("advanced");const a=e.getAttribute("data-display-mode");"overlay"!==a&&"popup"!==a&&"fullscreen"!==a||i.add("display"),(n.includes("form")||n.includes("input")||n.includes("contact")||"form"===s)&&i.add("security"),"gallery"!==s&&"interactive"!==s||i.add("messaging")}return e.debug("WidgeticBootstrap: Required features:",Array.from(i)),Array.from(i)}extractWidgetCapabilities(t){var i;const n=[];try{const e=t.getAttribute("data-widget-meta");if(e){const t=JSON.parse(e);(t.mediaCapabilities||t.supportsMedia)&&n.push("media"),(t.textCapabilities||t.supportsText||t.hasTextFields)&&n.push("security"),(t.supportsInteraction||t.hasInteractiveElements)&&n.push("messaging"),(t.supportsFullscreen||t.supportsOverlay)&&n.push("display"),(t.supportsABTesting||t.trackingCapabilities)&&n.push("abTesting")}const s=t.getAttribute("data-widget-type");if(s)switch(s){case"media":n.push("media");break;case"form":n.push("security","messaging");break;case"gallery":case"interactive":n.push("messaging")}if(t.matches("widgetic-widget[data-capabilities]")){const e=(null===(i=t.getAttribute("data-capabilities"))||void 0===i?void 0:i.split(","))||[];n.push(...e.map((t=>t.trim())))}}catch(t){e.debug("Failed to parse widget metadata, using fallback detection",{error:t})}return n}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(i){return t(this,void 0,void 0,(function*(){var t;const{getSDK:n}=yield import("./chunks/api.js").then((function(t){return t.p})),s=n({debug:this.config.debug,lazyLoading:{enabled:null===(t=this.config.enableLazyLoading)||void 0===t||t,config:{}}});yield s.init(),e.info(`WidgeticBootstrap: Processing ${i.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 o=null;function d(i){return t(this,void 0,void 0,(function*(){return o?(e.warn("WidgeticBootstrap: Already initialized"),o.getStats()):(o=new r(i),yield o.initialize())}))}function u(){return(null==o?void 0:o.getStats())||null}if("undefined"!=typeof document){const t=()=>{window.__WIDGETIC_SDK_INITIALIZED__||d({debug:"development"===n.NODE_ENV,preloadCritical:!0}).catch((t=>{e.error("WidgeticBootstrap: Auto-initialization failed",t)}))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):setTimeout(t,0)}"undefined"!=typeof window&&(window.WidgeticBootstrap={init:d,getStats:u,version:"1.0.0"});export{r as BootstrapManager,s as FastWidgetScanner,a as ProgressiveChunkLoader,u as getBootstrapStats,d as initializeWidgeticFast};
@@ -1 +1 @@
1
- import{j as r,W as c,k as l,l as h,m,n as E}from"./chunks/api.js";export{p as AuthError,A as AuthManager,B as BatchApiClient,C as CSSDebugger,D as DefaultTokenProvider,o as EndpointTokenProvider,F as FunctionTokenProvider,H as HighLevelAPI,L as LowLevelAPI,y as MidLevelAPI,s as ModuleLoader,S as StaticApiKeyProvider,w as analyzeWidgetCSS,v as disableCSSDebug,u as enableCSSDebug,g as getBatchClient,e as getModuleLoader,x as monitorWidgetCSS,q as resetBatchClient,t as resetModuleLoader}from"./chunks/api.js";import{l as T,d as _,V as R,h as M,e as O,a as N}from"./chunks/core.js";export{b as getApiUrl,n as getAuthManager,f as getCdnUrl,j as getConfiguration,k as getTokenProvider,s as setApiKey,i as setTokenProvider}from"./chunks/core.js";import{r as W,W as z}from"./chunks/renderers.js";export{C as CustomElementRenderer,I as IframeRenderer,a as WidgetRenderer,g as getWidgetRenderer,b as resetWidgetRenderer}from"./chunks/renderers.js";export{WidgeticMessenger,getMessenger,resetMessenger}from"./chunks/messaging.js";import{ABTestManager as P}from"./chunks/ABTestManager.js";import{_ as Q}from"./chunks/vendor.js";import{C as K,A as U,e as V}from"./chunks/advanced.js";export{f as toCamel,t as toSnake}from"./chunks/advanced.js";import{j as $}from"./chunks/scanner.js";export{d as detectBrowserCapabilities,f as determineBestRenderMode,e as isValidWidgetElement,p as parseWidgetConfig}from"./chunks/scanner.js";import"./chunks/media.js";import"./chunks/security.js";import"./chunks/performance.js";import"./chunks/display.js";class Y{constructor(e){this.deviceDetector=r(),this.privacyCompliance=null,this.eventQueue=[],this.batchTimer=null,this.isOnline=navigator.onLine,this.sessionStartTime=Date.now(),this.lastActivityTime=Date.now(),this.isSessionActive=!1,this.interactionCount=0,this.viewStartTime=Date.now(),this.STORAGE_KEY="widgetic_analytics_queue",this.SESSION_KEY="widgetic_session_id",this.config=Object.assign({batchSize:10,batchTimeout:5e3,maxRetries:3,rateLimitPerMinute:100,enableLocalStorage:!0,enableDeviceTracking:!0,enableInteractionTracking:!0,trackOnlyClicks:!0},e),this.sessionId=this.initializeSession(),this.rateLimitState={eventCounts:new Map,windowStart:Date.now(),windowDurationMs:6e4},this.setupEventListeners(),this.loadQueuedEvents(),T.debug("[AnalyticsTracker] Initialized",{compositionId:this.config.compositionId,sessionId:this.sessionId})}static getInstance(e){if(!Y.instance&&e&&(Y.instance=new Y(e)),!Y.instance)throw new Error("AnalyticsTracker must be initialized with config first");return Y.instance}initializeSession(){if(this.config.enableLocalStorage){const e=localStorage.getItem(this.SESSION_KEY);if(e)try{const t=JSON.parse(e);if(Date.now()-t.timestamp<18e5)return t.sessionId}catch(e){T.warn("[AnalyticsTracker] Failed to parse stored session",{error:e})}}const e=`sess_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;if(this.config.enableLocalStorage)try{localStorage.setItem(this.SESSION_KEY,JSON.stringify({sessionId:e,timestamp:Date.now()}))}catch(e){T.warn("[AnalyticsTracker] Failed to store session ID",{error:e})}return e}setPrivacyCompliance(e){this.privacyCompliance=e}isTrackingAllowed(){return!this.privacyCompliance||this.privacyCompliance.hasConsent("analytics")}setupEventListeners(){window.addEventListener("online",(()=>{this.isOnline=!0,this.processBatch()})),window.addEventListener("offline",(()=>{this.isOnline=!1})),["mousedown","mousemove","keypress","scroll","touchstart"].forEach((e=>{document.addEventListener(e,(()=>this.updateActivity()),{passive:!0})})),document.addEventListener("visibilitychange",(()=>{document.hidden?this.trackSessionEnd("visibility_hidden"):this.trackSessionStart()})),window.addEventListener("beforeunload",(()=>{this.trackSessionEnd("navigation"),this.flushEvents()}))}updateActivity(){this.lastActivityTime=Date.now(),this.isSessionActive||this.trackSessionStart()}isRateLimited(e){const t=Date.now();t-this.rateLimitState.windowStart>=this.rateLimitState.windowDurationMs&&(this.rateLimitState.eventCounts.clear(),this.rateLimitState.windowStart=t);const i=this.rateLimitState.eventCounts.get(e)||0;return i>=this.config.rateLimitPerMinute?(T.warn("[AnalyticsTracker] Rate limit exceeded",{eventType:e,currentCount:i}),!0):(this.rateLimitState.eventCounts.set(e,i+1),!1)}generateEventId(){return`evt_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}createBaseEvent(e,t={}){const i=this.config.enableDeviceTracking?this.deviceDetector.getDeviceInfo():void 0;return{id:this.generateEventId(),eventType:e,compositionId:this.config.compositionId,timestamp:Date.now(),sessionId:this.sessionId,data:t,deviceInfo:i,referrer:document.referrer||void 0,userAgent:navigator.userAgent,url:window.location.href}}queueEvent(e){this.isTrackingAllowed()?this.isRateLimited(e.eventType)||(this.eventQueue.push(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),this.scheduleBatch(),T.debug("[AnalyticsTracker] Event queued",{eventType:e.eventType,queueSize:this.eventQueue.length})):T.debug("[AnalyticsTracker] Tracking not allowed, skipping event",{eventType:e.eventType})}scheduleBatch(){this.eventQueue.length>=this.config.batchSize?this.processBatch():this.batchTimer||(this.batchTimer=setTimeout((()=>{this.processBatch()}),this.config.batchTimeout))}processBatch(){return Q(this,void 0,void 0,(function*(){if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),0===this.eventQueue.length||!this.isOnline)return;const e=this.eventQueue.splice(0,this.config.batchSize);try{yield this.sendEventBatch(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),T.debug("[AnalyticsTracker] Batch sent successfully",{batchSize:e.length,remainingQueue:this.eventQueue.length})}catch(t){T.error("[AnalyticsTracker] Failed to send batch",{error:t,batchSize:e.length}),this.eventQueue.unshift(...e),setTimeout((()=>this.processBatch()),5e3)}}))}sendEventBatch(e){return Q(this,void 0,void 0,(function*(){if(!this.config.apiEndpoint)return void T.warn("[AnalyticsTracker] No API endpoint configured");const t=e.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer,ip_address:void 0}))),i=yield _(),n=new K({basePath:this.config.apiEndpoint,accessToken:()=>Q(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${R}`}}),s=new U(n);yield s.analyticsEventsBulkPost({analyticsEventsBulkPostRequest:{events:t}})}))}saveQueueToStorage(){if(this.config.enableLocalStorage)try{const e={events:this.eventQueue,timestamp:Date.now()};localStorage.setItem(this.STORAGE_KEY,JSON.stringify(e))}catch(e){T.warn("[AnalyticsTracker] Failed to save queue to storage",{error:e})}}loadQueuedEvents(){if(this.config.enableLocalStorage)try{const e=localStorage.getItem(this.STORAGE_KEY);if(e){const t=JSON.parse(e);Date.now()-t.timestamp<864e5?(this.eventQueue=t.events||[],T.debug("[AnalyticsTracker] Loaded queued events from storage",{count:this.eventQueue.length})):localStorage.removeItem(this.STORAGE_KEY)}}catch(e){T.warn("[AnalyticsTracker] Failed to load queued events from storage",{error:e}),localStorage.removeItem(this.STORAGE_KEY)}}flushEvents(){if(0!==this.eventQueue.length&&navigator.sendBeacon&&this.config.apiEndpoint){const e=this.eventQueue.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer})));navigator.sendBeacon(`${this.config.apiEndpoint}/analytics/events/bulk`,JSON.stringify({events:e})),this.eventQueue=[]}}trackCompositionView(e={}){const t=Object.assign({viewportSize:{width:window.innerWidth,height:window.innerHeight},scrollPosition:{x:window.scrollX,y:window.scrollY},loadTime:Date.now()-this.viewStartTime},e),i=this.createBaseEvent("composition_view",t);this.queueEvent(i)}trackCompositionInteraction(e){if(this.config.trackOnlyClicks&&"hover"===e.interactionType)return;this.interactionCount++,this.updateActivity();const t=this.createBaseEvent("composition_interaction",e);this.queueEvent(t)}trackSessionStart(){if(this.isSessionActive)return;this.isSessionActive=!0,this.sessionStartTime=Date.now();const e=this.createBaseEvent("session_start",{sessionDuration:0,pageViews:1,interactions:0});this.queueEvent(e)}trackSessionEnd(e="user_close"){if(!this.isSessionActive)return;this.isSessionActive=!1;const t={sessionDuration:Date.now()-this.sessionStartTime,interactions:this.interactionCount,exitReason:e},i=this.createBaseEvent("session_end",t);this.queueEvent(i)}trackDeviceInfo(){if(!this.config.enableDeviceTracking)return;const e=this.deviceDetector.getDeviceInfo(),t=this.createBaseEvent("device_info",e);this.queueEvent(t)}trackReferrerInfo(){const e={referrer:document.referrer,referrer_domain:document.referrer?new URL(document.referrer).hostname:null,current_url:window.location.href,current_domain:window.location.hostname},t=this.createBaseEvent("referrer_info",e);this.queueEvent(t)}getSessionInfo(){return{sessionId:this.sessionId,isActive:this.isSessionActive,startTime:this.sessionStartTime,lastActivity:this.lastActivityTime,interactionCount:this.interactionCount,duration:Date.now()-this.sessionStartTime}}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e),T.debug("[AnalyticsTracker] Configuration updated",e)}clearQueue(){this.eventQueue=[],this.config.enableLocalStorage&&localStorage.removeItem(this.STORAGE_KEY),T.debug("[AnalyticsTracker] Event queue cleared")}getStats(){return{queueSize:this.eventQueue.length,sessionInfo:this.getSessionInfo(),rateLimits:Object.fromEntries(this.rateLimitState.eventCounts),isOnline:this.isOnline,trackingAllowed:this.isTrackingAllowed()}}destroy(){this.trackSessionEnd("destroy"),this.flushEvents(),this.batchTimer&&clearTimeout(this.batchTimer),this.config.enableLocalStorage&&(localStorage.removeItem(this.STORAGE_KEY),localStorage.removeItem(this.SESSION_KEY)),Y.instance=null,T.debug("[AnalyticsTracker] Destroyed")}}const G="undefined"!=typeof HTMLElement?HTMLElement:class{};class J extends G{constructor(){super(),this.experimentId=null,this.assignment=null,this.widgetInstance=null,this.impressionTracked=!1,this.conversionListeners=new Map,this.manager=P.getInstance(),this.widgetManager=c.getInstance(),this.analyticsTracker=Y.getInstance(),this.attachShadow({mode:"open"}),this.setupEventListeners()}static get observedAttributes(){return["experiment-id","user-id","session-id"]}connectedCallback(){return Q(this,void 0,void 0,(function*(){try{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return M.error("A/B test element missing experiment-id attribute"),void this.renderError("Missing experiment-id attribute");const e={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0,userAgent:navigator.userAgent,ipAddress:void 0};if(this.renderLoading(),this.assignment=yield this.manager.getVariantAssignment(this.experimentId,e),!this.assignment)return M.warn("No variant assignment received",{experimentId:this.experimentId}),void this.renderError("Test not available");yield this.renderVariant(),yield this.trackImpression(),this.setupConversionTracking(),M.info("A/B test element initialized",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){M.error("Failed to initialize A/B test element",{experimentId:this.experimentId,error:e}),this.renderError("Failed to load test")}}))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,i){t!==i&&"experiment-id"===e&&this.connectedCallback()}setupEventListeners(){this.manager.on("conversion",(e=>{e.experimentId===this.experimentId&&this.handleConversionEvent(e)})),this.widgetManager.addEventListener("widget_ready",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetReady(e)})),this.widgetManager.addEventListener("widget_error",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetError(e)}))}renderVariant(){return Q(this,void 0,void 0,(function*(){var e,t,i;if(this.assignment&&this.shadowRoot)try{const i=document.createElement("div");i.style.cssText="\n width: 100%;\n height: 100%;\n position: relative;\n ",i.setAttribute("data-ab-experiment",this.experimentId||""),i.setAttribute("data-ab-variant",this.assignment.variantId);const n=this.createEmbedElement(this.assignment.embedCode);if(n){i.appendChild(n);const s={compositionId:this.assignment.compositionId,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};this.widgetInstance=yield this.widgetManager.registerWidget(`abtest_${this.experimentId}_${this.assignment.variantId}_${Date.now()}`,s,n),this.widgetInstance&&(null===(e=this.widgetInstance.element)||void 0===e||e.setAttribute("data-ab-experiment-id",this.experimentId||""),null===(t=this.widgetInstance.element)||void 0===t||t.setAttribute("data-ab-variant-id",this.assignment.variantId))}this.shadowRoot.innerHTML="",this.shadowRoot.appendChild(i),this.dispatchEvent(new CustomEvent("variant-rendered",{detail:{experimentId:this.experimentId,variantId:this.assignment.variantId,compositionId:this.assignment.compositionId},bubbles:!0}))}catch(e){M.error("Failed to render variant",{experimentId:this.experimentId,variantId:null===(i=this.assignment)||void 0===i?void 0:i.variantId,error:e}),this.renderError("Failed to render variant")}}))}createEmbedElement(e){var t;try{const i=new DOMParser,n=i.parseFromString(e,"text/html").body.firstElementChild;if(!n)return M.warn("No element found in embed code",{embedCode:e}),null;const s=n.cloneNode(!0);return s.setAttribute("data-ab-experiment",this.experimentId||""),s.setAttribute("data-ab-variant",(null===(t=this.assignment)||void 0===t?void 0:t.variantId)||""),s}catch(t){return M.error("Failed to parse embed code",{embedCode:e,error:t}),null}}setupConversionTracking(){if(this.assignment&&this.widgetInstance)try{this.setupClickTracking(),this.setupFormTracking(),this.setupMediaTracking(),this.setupCustomEventTracking(),M.debug("Conversion tracking setup complete",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){M.error("Failed to setup conversion tracking",{experimentId:this.experimentId,error:e})}}setupClickTracking(){const e=e=>{var t;if(!this.experimentId||!this.assignment)return;const i=e.target;this.isClickableElement(i)&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"clicks",{element:i.tagName.toLowerCase(),text:(null===(t=i.textContent)||void 0===t?void 0:t.slice(0,100))||"",timestamp:Date.now()})};this.shadowRoot&&(this.shadowRoot.addEventListener("click",e),this.conversionListeners.set("click",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("click",e)})))}setupFormTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target;"FORM"===t.tagName&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"submissions",{formId:t.id||"unknown",timestamp:Date.now()})};this.shadowRoot&&(this.shadowRoot.addEventListener("submit",e),this.conversionListeners.set("submit",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("submit",e)})))}setupMediaTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target;"VIDEO"!==t.tagName&&"AUDIO"!==t.tagName||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"plays",{mediaType:t.tagName.toLowerCase(),duration:t.duration||0,timestamp:Date.now()})};this.shadowRoot&&(this.shadowRoot.addEventListener("play",e),this.conversionListeners.set("play",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("play",e)})))}setupCustomEventTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.detail;this.manager.trackConversion(this.experimentId,this.assignment.variantId,t.type||"conversions",Object.assign(Object.assign({},t),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("widgetic:conversion",e),this.conversionListeners.set("conversion",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("widgetic:conversion",e)})))}isClickableElement(e){return["BUTTON","A","INPUT"].includes(e.tagName)||e.hasAttribute("onclick")||e.hasAttribute("data-click-track")||"INPUT"===e.tagName&&["button","submit"].includes(e.type)||"button"===e.getAttribute("role")}trackImpression(){return Q(this,void 0,void 0,(function*(){if(!this.impressionTracked&&this.experimentId&&this.assignment)try{const e={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0};yield this.manager.trackImpression(this.experimentId,this.assignment.variantId,e),this.impressionTracked=!0,this.analyticsTracker.trackCompositionView({experiment_id:this.experimentId,variant_id:this.assignment.variantId,composition_id:this.assignment.compositionId}),M.debug("Impression tracked",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){M.error("Failed to track impression",{experimentId:this.experimentId,error:e})}}))}handleConversionEvent(e){this.dispatchEvent(new CustomEvent("conversion",{detail:e,bubbles:!0})),this.analyticsTracker.trackCompositionInteraction({interactionType:"click",elementType:"ab_test_conversion",elementId:e.experimentId,coordinates:{x:0,y:0},duration:0})}onWidgetReady(e){var t,i;M.debug("Widget ready for A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,widgetId:e.widgetId}),this.dispatchEvent(new CustomEvent("widget-ready",{detail:{experimentId:this.experimentId,variantId:null===(i=this.assignment)||void 0===i?void 0:i.variantId,widgetId:e.widgetId},bubbles:!0}))}onWidgetError(e){var t;M.error("Widget error in A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,error:e.details}),this.renderError("Widget failed to load")}renderLoading(){this.shadowRoot&&(this.shadowRoot.innerHTML='\n <style>\n .ab-test-loading {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #666;\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n }\n .spinner {\n width: 20px;\n height: 20px;\n border: 2px solid #e0e0e0;\n border-top: 2px solid #007cba;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin-right: 10px;\n }\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n <div class="ab-test-loading">\n <div class="spinner"></div>\n Loading test...\n </div>\n ')}renderError(e){this.shadowRoot&&(this.shadowRoot.innerHTML=`\n <style>\n .ab-test-error {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #d32f2f;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background-color: #ffebee;\n border: 1px solid #ffcdd2;\n border-radius: 4px;\n padding: 16px;\n text-align: center;\n }\n </style>\n <div class="ab-test-error">\n ${e}\n </div>\n `,this.dispatchEvent(new CustomEvent("error",{detail:{message:e},bubbles:!0})))}cleanup(){if(this.conversionListeners.forEach((e=>e())),this.conversionListeners.clear(),this.widgetInstance)try{this.widgetManager.unregisterWidget(this.widgetInstance.id)}catch(e){M.warn("Failed to cleanup widget instance",{error:e})}this.impressionTracked=!1,this.assignment=null,this.widgetInstance=null}trackConversion(e="custom",t){return this.experimentId&&this.assignment?this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,t):Promise.reject(new Error("A/B test not initialized"))}getAssignment(){return this.assignment?Object.assign({},this.assignment):null}getExperimentId(){return this.experimentId}static register(){"undefined"!=typeof window&&window.customElements&&(customElements.get("widgetic-abtest")||customElements.define("widgetic-abtest",J))}}J.register();const X="undefined"!=typeof HTMLElement?HTMLElement:class{};class Z extends X{constructor(){super(),this.widgetInstance=null,this.isInitialized=!1,this.retryCount=0,this.maxRetries=3,this.retryDelay=1e3,this.experimentId=null,this.selectedLanguage=null,this.translationData=null,this.widgetManager=l(),T.debug("[TranslationElement] Created translation element")}connectedCallback(){if(this.isInitialized)T.debug("[TranslationElement] Already initialized, skipping");else{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return T.error("[TranslationElement] Missing experiment-id attribute"),void this.displayError("Missing experiment-id attribute");T.debug(`[TranslationElement] Connected with experiment ID: ${this.experimentId}`),this.initializeTranslation()}}disconnectedCallback(){T.debug("[TranslationElement] Disconnected"),this.cleanup()}initializeTranslation(){return Q(this,void 0,void 0,(function*(){try{this.isInitialized=!0;const e=this.detectBrowserLanguages();if(T.debug("[TranslationElement] Detected user languages:",e),this.translationData=yield this.fetchTranslationExperiment(this.experimentId),!this.translationData)throw new Error("Failed to fetch translation experiment data");this.selectedLanguage=this.findBestLanguageMatch(e,this.translationData),T.debug("[TranslationElement] Selected language:",this.selectedLanguage);const t=this.getCompositionForLanguage(this.selectedLanguage);if(!t)throw new Error(`No composition found for language: ${this.selectedLanguage}`);yield this.loadWidget(t),T.info("[TranslationElement] Translation experiment loaded successfully",{experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,compositionId:t})}catch(e){T.error("[TranslationElement] Failed to initialize translation:",e),yield this.handleInitializationError(e)}}))}detectBrowserLanguages(){var e;const t=navigator.language.toLowerCase(),i=((null===(e=navigator.languages)||void 0===e?void 0:e.map((e=>e.toLowerCase())))||[t]).flatMap((e=>{const t=[e];return e.includes("-")&&t.push(e.split("-")[0]),t}));return[...new Set(i)]}fetchTranslationExperiment(e){return Q(this,void 0,void 0,(function*(){try{const t=O(),i=new K({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new V(i),s=yield n.getTranslationConfig({id:e});return(null==s?void 0:s.data)||null}catch(e){throw T.error("[TranslationElement] Error fetching translation experiment:",e),e}}))}findBestLanguageMatch(e,t){const i=Object.keys(t.languageCompositions||{}),n=t.rootLanguage||"en";T.debug("[TranslationElement] Available languages:",i),T.debug("[TranslationElement] Root language:",n);for(const t of e)if(i.includes(t))return T.debug("[TranslationElement] Found exact match:",t),t;for(const t of e){const e=t.split("-")[0],n=i.find((t=>t.startsWith(e+"-")||t===e));if(n)return T.debug("[TranslationElement] Found base language match:",n),this.trackFallbackUsage(t,n,"language_family").catch((e=>{T.debug("[TranslationElement] Failed to track language family fallback:",e)})),n}T.debug("[TranslationElement] No matches found, falling back to root language:",n);const s=e[0]||"unknown";return this.trackFallbackUsage(s,n,"root_fallback").catch((e=>{T.debug("[TranslationElement] Failed to track root fallback:",e)})),n}getCompositionForLanguage(e){if(!this.translationData)return null;if(e===this.translationData.rootLanguage)return this.translationData.rootCompositionId;return(this.translationData.languageCompositions||{})[e]||this.translationData.rootCompositionId}loadWidget(e){return Q(this,void 0,void 0,(function*(){const t=$(e),i={compositionId:e,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};this.widgetInstance=yield this.widgetManager.registerWidget(t,i,this),this.trackTranslationView()}))}trackTranslationView(){try{const e={experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,userLanguages:this.detectBrowserLanguages(),timestamp:(new Date).toISOString(),userAgent:navigator.userAgent,referrer:document.referrer,url:window.location.href};this.sendAnalytics(e).catch((e=>{T.warn("[TranslationElement] Failed to send analytics:",e)}))}catch(e){T.warn("[TranslationElement] Error in analytics tracking:",e)}}sendAnalytics(e){return Q(this,void 0,void 0,(function*(){try{const t=O(),i=new K({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new V(i);yield n.submitTranslationAnalyticsEvent({id:this.experimentId,submitTranslationAnalyticsEventRequest:e})}catch(e){T.debug("[TranslationElement] Analytics request failed:",e)}}))}trackFallbackUsage(e,t,i){return Q(this,void 0,void 0,(function*(){try{const n={eventType:"fallback_used",language:t,compositionId:this.getCompositionForLanguage(t)||"",metadata:{requestedLanguage:e,selectedLanguage:t,fallbackType:i,userAgent:navigator.userAgent,timestamp:(new Date).toISOString()},timestamp:(new Date).toISOString()};yield this.sendAnalytics(n),T.debug("[TranslationElement] Fallback usage tracked:",{requested:e,selected:t,fallbackType:i})}catch(e){T.debug("[TranslationElement] Failed to track fallback usage:",e)}}))}handleInitializationError(e){return Q(this,void 0,void 0,(function*(){if(this.retryCount<this.maxRetries){this.retryCount++,T.warn(`[TranslationElement] Retrying initialization (${this.retryCount}/${this.maxRetries}):`,e.message),yield new Promise((e=>setTimeout(e,this.retryDelay*this.retryCount)));try{return void(yield this.initializeTranslation())}catch(e){T.error("[TranslationElement] Retry failed:",e)}}this.displayError(`Translation loading failed: ${e.message}`)}))}displayError(e){this.innerHTML=`\n <div style="\n padding: 1rem;\n border: 1px solid #ef4444;\n border-radius: 0.5rem;\n background-color: #fef2f2;\n color: #dc2626;\n font-family: system-ui, -apple-system, sans-serif;\n font-size: 0.875rem;\n margin: 1rem 0;\n ">\n <strong>Translation Error:</strong> ${e}\n </div>\n `}cleanup(){this.widgetInstance&&(this.widgetManager.unregisterWidget(this.widgetInstance.id),this.widgetInstance=null),this.isInitialized=!1,this.retryCount=0}switchLanguage(e){if(!this.translationData)throw new Error("Translation data not loaded");const t=this.getCompositionForLanguage(e);if(!t)throw new Error(`No composition found for language: ${e}`);return this.cleanup(),this.selectedLanguage=e,this.loadWidget(t)}getSelectedLanguage(){return this.selectedLanguage}getAvailableLanguages(){return this.translationData?Object.keys(this.translationData.languageCompositions||{}):[]}static register(){try{"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-translations")||(customElements.define("widgetic-translations",Z),T.info("[TranslationElement] Custom element registered")))}catch(e){T.error("[TranslationElement] Failed to register custom element:",e)}}}Z.register();const ee=h();"undefined"!=typeof window&&"undefined"!=typeof customElements&&(W(),J.register(),Z.register()),"undefined"!=typeof window&&(window.WidgeticEmbedSDK=ee,window.Widgetic={SDK:ee,getSDK:h,EmbedSDK:m,config:{API_URL:N.API_URL,API_VERSION:N.API_VERSION,CLIENT_URL:N.CLIENT_URL,PRODUCTION_URL:N.PRODUCTION_URL,NODE_ENV:N.NODE_ENV},log:T,WidgeticWidget:z,registerWidgeticWidget:W,cssDebugger:E,enableCSSDebug:()=>E.enableDebugMode(),disableCSSDebug:()=>E.disableDebugMode(),analyzeWidget:e=>E.analyzeWidget(e),ABTestManager:P,ABTestElement:J,TranslationElement:Z});export{J as ABTestElement,P as ABTestManager,m as EmbedSDK,Z as TranslationElement,m as WidgeticEmbedSDK,z as WidgeticWidget,N as config,E as cssDebugger,ee as default,$ as generateInstanceId,_ as getAuthToken,h as getSDK,T as log,W as registerWidgeticWidget};
1
+ import{b as e,W as n,c as o,G as u,d as v,e as w,f as b,E as y}from"./chunks/api.js";export{B as BatchApiClient,C as CSSDebugger,H as HighLevelAPI,L as LowLevelAPI,M as MidLevelAPI,h as ModuleLoader,i as analyzeWidgetCSS,j as disableCSSDebug,k as enableCSSDebug,g as getBatchClient,a as getModuleLoader,m as monitorWidgetCSS,r as resetBatchClient,l as resetModuleLoader}from"./chunks/api.js";import{l as T,g as x,C as D,V as _,q as R,e as O,a as W,T as N,d as z}from"./chunks/core.js";export{r as AuthError,A as AuthManager,j as DefaultTokenProvider,E as EndpointTokenProvider,F as FunctionTokenProvider,S as StaticApiKeyProvider,m as getApiUrl,t as getAuthManager,c as getCdnUrl,h as getConfiguration,k as getTokenProvider,i as setApiKey,s as setTokenProvider}from"./chunks/core.js";import{e as P,W as Q}from"./chunks/renderers.js";export{C as CustomElementRenderer,I as IframeRenderer,f as WidgetRenderer,g as getWidgetRenderer,h as resetWidgetRenderer}from"./chunks/renderers.js";export{WidgeticMessenger,getMessenger,resetMessenger}from"./chunks/messaging.js";import{A as q,e as K}from"./chunks/ABTestManager.js";import{_ as U}from"./chunks/vendor.js";import{l as V}from"./chunks/scanner.js";export{f as detectBrowserCapabilities,k as determineBestRenderMode,j as isValidWidgetElement,p as parseWidgetConfig}from"./chunks/scanner.js";export{d as toCamel,t as toSnake}from"./chunks/advanced.js";import"./chunks/media.js";import"./chunks/security.js";import"./chunks/performance.js";import"./chunks/display.js";class ${constructor(t){this.deviceDetector=e(),this.privacyCompliance=null,this.eventQueue=[],this.batchTimer=null,this.isOnline=navigator.onLine,this.sessionStartTime=Date.now(),this.lastActivityTime=Date.now(),this.isSessionActive=!1,this.interactionCount=0,this.viewStartTime=Date.now(),this.STORAGE_KEY="widgetic_analytics_queue",this.SESSION_KEY="widgetic_session_id",this.config=Object.assign({batchSize:10,batchTimeout:5e3,maxRetries:3,rateLimitPerMinute:100,enableLocalStorage:!0,enableDeviceTracking:!0,enableInteractionTracking:!0,trackOnlyClicks:!0},t),this.sessionId=this.initializeSession(),this.rateLimitState={eventCounts:new Map,windowStart:Date.now(),windowDurationMs:6e4},this.setupEventListeners(),this.loadQueuedEvents(),T.debug("[AnalyticsTracker] Initialized",{compositionId:this.config.compositionId,sessionId:this.sessionId})}static getInstance(e){if(!$.instance&&e&&($.instance=new $(e)),!$.instance)throw new Error("AnalyticsTracker must be initialized with config first");return $.instance}initializeSession(){if(this.config.enableLocalStorage){const e=localStorage.getItem(this.SESSION_KEY);if(e)try{const t=JSON.parse(e);if(Date.now()-t.timestamp<18e5)return t.sessionId}catch(e){T.warn("[AnalyticsTracker] Failed to parse stored session",{error:e})}}const e=`sess_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;if(this.config.enableLocalStorage)try{localStorage.setItem(this.SESSION_KEY,JSON.stringify({sessionId:e,timestamp:Date.now()}))}catch(e){T.warn("[AnalyticsTracker] Failed to store session ID",{error:e})}return e}setPrivacyCompliance(e){this.privacyCompliance=e}isTrackingAllowed(){return!this.privacyCompliance||this.privacyCompliance.hasConsent("analytics")}setupEventListeners(){window.addEventListener("online",(()=>{this.isOnline=!0,this.processBatch()})),window.addEventListener("offline",(()=>{this.isOnline=!1})),["mousedown","mousemove","keypress","scroll","touchstart"].forEach((e=>{document.addEventListener(e,(()=>this.updateActivity()),{passive:!0})})),document.addEventListener("visibilitychange",(()=>{document.hidden?this.trackSessionEnd("visibility_hidden"):this.trackSessionStart()})),window.addEventListener("beforeunload",(()=>{this.trackSessionEnd("navigation"),this.flushEvents()}))}updateActivity(){this.lastActivityTime=Date.now(),this.isSessionActive||this.trackSessionStart()}isRateLimited(e){const t=Date.now();t-this.rateLimitState.windowStart>=this.rateLimitState.windowDurationMs&&(this.rateLimitState.eventCounts.clear(),this.rateLimitState.windowStart=t);const i=this.rateLimitState.eventCounts.get(e)||0;return i>=this.config.rateLimitPerMinute?(T.warn("[AnalyticsTracker] Rate limit exceeded",{eventType:e,currentCount:i}),!0):(this.rateLimitState.eventCounts.set(e,i+1),!1)}generateEventId(){return`evt_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}createBaseEvent(e,t={}){const i=this.config.enableDeviceTracking?this.deviceDetector.getDeviceInfo():void 0;return{id:this.generateEventId(),eventType:e,compositionId:this.config.compositionId,timestamp:Date.now(),sessionId:this.sessionId,data:t,deviceInfo:i,referrer:document.referrer||void 0,userAgent:navigator.userAgent,url:window.location.href}}queueEvent(e){this.isTrackingAllowed()?this.isRateLimited(e.eventType)||(this.eventQueue.push(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),this.scheduleBatch(),T.debug("[AnalyticsTracker] Event queued",{eventType:e.eventType,queueSize:this.eventQueue.length})):T.debug("[AnalyticsTracker] Tracking not allowed, skipping event",{eventType:e.eventType})}scheduleBatch(){this.eventQueue.length>=this.config.batchSize?this.processBatch():this.batchTimer||(this.batchTimer=setTimeout((()=>{this.processBatch()}),this.config.batchTimeout))}processBatch(){return U(this,void 0,void 0,(function*(){if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),0===this.eventQueue.length||!this.isOnline)return;const e=this.eventQueue.splice(0,this.config.batchSize);try{yield this.sendEventBatch(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),T.debug("[AnalyticsTracker] Batch sent successfully",{batchSize:e.length,remainingQueue:this.eventQueue.length})}catch(t){T.error("[AnalyticsTracker] Failed to send batch",{error:t,batchSize:e.length}),this.eventQueue.unshift(...e),setTimeout((()=>this.processBatch()),5e3)}}))}sendEventBatch(e){return U(this,void 0,void 0,(function*(){if(!this.config.apiEndpoint)return void T.warn("[AnalyticsTracker] No API endpoint configured");const t=e.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer,ip_address:void 0}))),i=yield x(),n=new D({basePath:this.config.apiEndpoint,accessToken:()=>U(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${_}`}}),s=new R(n);yield s.analyticsEventsBulkPost({analyticsEventsBulkPostRequest:{events:t}})}))}saveQueueToStorage(){if(this.config.enableLocalStorage)try{const e={events:this.eventQueue,timestamp:Date.now()};localStorage.setItem(this.STORAGE_KEY,JSON.stringify(e))}catch(e){T.warn("[AnalyticsTracker] Failed to save queue to storage",{error:e})}}loadQueuedEvents(){if(this.config.enableLocalStorage)try{const e=localStorage.getItem(this.STORAGE_KEY);if(e){const t=JSON.parse(e);Date.now()-t.timestamp<864e5?(this.eventQueue=t.events||[],T.debug("[AnalyticsTracker] Loaded queued events from storage",{count:this.eventQueue.length})):localStorage.removeItem(this.STORAGE_KEY)}}catch(e){T.warn("[AnalyticsTracker] Failed to load queued events from storage",{error:e}),localStorage.removeItem(this.STORAGE_KEY)}}flushEvents(){if(0!==this.eventQueue.length&&navigator.sendBeacon&&this.config.apiEndpoint){const e=this.eventQueue.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer})));navigator.sendBeacon(`${this.config.apiEndpoint}/analytics/events/bulk`,JSON.stringify({events:e})),this.eventQueue=[]}}trackCompositionView(e={}){const t=Object.assign({viewportSize:{width:window.innerWidth,height:window.innerHeight},scrollPosition:{x:window.scrollX,y:window.scrollY},loadTime:Date.now()-this.viewStartTime},e),i=this.createBaseEvent("composition_view",t);this.queueEvent(i)}trackCompositionInteraction(e){if(this.config.trackOnlyClicks&&"hover"===e.interactionType)return;this.interactionCount++,this.updateActivity();const t=this.createBaseEvent("composition_interaction",e);this.queueEvent(t)}trackSessionStart(){if(this.isSessionActive)return;this.isSessionActive=!0,this.sessionStartTime=Date.now();const e=this.createBaseEvent("session_start",{sessionDuration:0,pageViews:1,interactions:0});this.queueEvent(e)}trackSessionEnd(e="user_close"){if(!this.isSessionActive)return;this.isSessionActive=!1;const t={sessionDuration:Date.now()-this.sessionStartTime,interactions:this.interactionCount,exitReason:e},i=this.createBaseEvent("session_end",t);this.queueEvent(i)}trackDeviceInfo(){if(!this.config.enableDeviceTracking)return;const e=this.deviceDetector.getDeviceInfo(),t=this.createBaseEvent("device_info",e);this.queueEvent(t)}trackReferrerInfo(){const e={referrer:document.referrer,referrer_domain:document.referrer?new URL(document.referrer).hostname:null,current_url:window.location.href,current_domain:window.location.hostname},t=this.createBaseEvent("referrer_info",e);this.queueEvent(t)}getSessionInfo(){return{sessionId:this.sessionId,isActive:this.isSessionActive,startTime:this.sessionStartTime,lastActivity:this.lastActivityTime,interactionCount:this.interactionCount,duration:Date.now()-this.sessionStartTime}}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e),T.debug("[AnalyticsTracker] Configuration updated",e)}clearQueue(){this.eventQueue=[],this.config.enableLocalStorage&&localStorage.removeItem(this.STORAGE_KEY),T.debug("[AnalyticsTracker] Event queue cleared")}getStats(){return{queueSize:this.eventQueue.length,sessionInfo:this.getSessionInfo(),rateLimits:Object.fromEntries(this.rateLimitState.eventCounts),isOnline:this.isOnline,trackingAllowed:this.isTrackingAllowed()}}destroy(){this.trackSessionEnd("destroy"),this.flushEvents(),this.batchTimer&&clearTimeout(this.batchTimer),this.config.enableLocalStorage&&(localStorage.removeItem(this.STORAGE_KEY),localStorage.removeItem(this.SESSION_KEY)),$.instance=null,T.debug("[AnalyticsTracker] Destroyed")}}const G="undefined"!=typeof HTMLElement?HTMLElement:class{};class Y extends G{constructor(){super(),this.experimentId=null,this.assignment=null,this.widgetInstance=null,this.impressionTracked=!1,this.conversionListeners=new Map,this.manager=q.getInstance(),this.widgetManager=n.getInstance(),this.analyticsTracker=$.getInstance(),this.attachShadow({mode:"open"}),this.setupEventListeners()}static get observedAttributes(){return["experiment-id","user-id","session-id"]}connectedCallback(){return U(this,void 0,void 0,(function*(){try{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return O.error("A/B test element missing experiment-id attribute"),void this.renderError("Missing experiment-id attribute");const e={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0,userAgent:navigator.userAgent,ipAddress:void 0};if(this.renderLoading(),this.assignment=yield this.manager.getVariantAssignment(this.experimentId,e),!this.assignment)return O.warn("No variant assignment received",{experimentId:this.experimentId}),void this.renderError("Test not available");this.setupGoalListeners(),yield this.renderVariant(),yield this.trackImpression(),this.setupConversionTracking(),O.info("A/B test element initialized",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){O.error("Failed to initialize A/B test element",{experimentId:this.experimentId,error:e}),this.renderError("Failed to load test")}}))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,i){t!==i&&"experiment-id"===e&&this.connectedCallback()}setupEventListeners(){this.manager.on("conversion",(e=>{e.experimentId===this.experimentId&&this.handleConversionEvent(e)})),this.widgetManager.addEventListener("widget_ready",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetReady(e)})),this.widgetManager.addEventListener("widget_error",(e=>{this.widgetInstance&&e.widgetId===this.widgetInstance.id&&this.onWidgetError(e)}))}renderVariant(){return U(this,void 0,void 0,(function*(){var e,t,i;if(this.assignment&&this.shadowRoot)try{const i=document.createElement("div");i.style.cssText="\n width: 100%;\n height: 100%;\n position: relative;\n ",i.setAttribute("data-ab-experiment",this.experimentId||""),i.setAttribute("data-ab-variant",this.assignment.variantId);const n=this.createEmbedElement(this.assignment.embedCode);if(n){i.appendChild(n);const s={compositionId:this.assignment.compositionId,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};this.widgetInstance=yield this.widgetManager.registerWidget(`abtest_${this.experimentId}_${this.assignment.variantId}_${Date.now()}`,s,n),this.widgetInstance&&(null===(e=this.widgetInstance.element)||void 0===e||e.setAttribute("data-ab-experiment-id",this.experimentId||""),null===(t=this.widgetInstance.element)||void 0===t||t.setAttribute("data-ab-variant-id",this.assignment.variantId))}this.shadowRoot.innerHTML="",this.shadowRoot.appendChild(i),n&&this.sendGoalToWidget(n),this.dispatchEvent(new CustomEvent("variant-rendered",{detail:{experimentId:this.experimentId,variantId:this.assignment.variantId,compositionId:this.assignment.compositionId},bubbles:!0}))}catch(e){O.error("Failed to render variant",{experimentId:this.experimentId,variantId:null===(i=this.assignment)||void 0===i?void 0:i.variantId,error:e}),this.renderError("Failed to render variant")}}))}createEmbedElement(e){var t;try{const i=new DOMParser,n=i.parseFromString(e,"text/html").body.firstElementChild;if(!n)return O.warn("No element found in embed code",{embedCode:e}),null;const s=n.cloneNode(!0);return s.setAttribute("data-ab-experiment",this.experimentId||""),s.setAttribute("data-ab-variant",(null===(t=this.assignment)||void 0===t?void 0:t.variantId)||""),s}catch(t){return O.error("Failed to parse embed code",{embedCode:e,error:t}),null}}setupConversionTracking(){if(this.assignment&&this.widgetInstance)try{this.setupClickTracking(),this.setupFormTracking(),this.setupMediaTracking(),this.setupCustomEventTracking(),O.debug("Conversion tracking setup complete",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){O.error("Failed to setup conversion tracking",{experimentId:this.experimentId,error:e})}}setupClickTracking(){const e=e=>{var t;if(!this.experimentId||!this.assignment)return;const i=e.target,n=this.assignment.goalTarget||null;(n?K(i,n):this.isClickableElement(i))&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,"clicks",Object.assign(Object.assign({element:i.tagName.toLowerCase(),text:(null===(t=i.textContent)||void 0===t?void 0:t.slice(0,100))||""},n?{goalTarget:n}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("click",e),this.conversionListeners.set("click",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("click",e)})))}setupFormTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target,i=this.assignment.goalTarget||null;"FORM"!==t.tagName||i&&!K(t,i)||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"submissions",Object.assign(Object.assign({formId:t.id||"unknown"},i?{goalTarget:i}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("submit",e),this.conversionListeners.set("submit",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("submit",e)})))}setupMediaTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.target,i=this.assignment.goalTarget||null;"VIDEO"!==t.tagName&&"AUDIO"!==t.tagName||i&&!K(t,i)||this.manager.trackConversion(this.experimentId,this.assignment.variantId,"plays",Object.assign(Object.assign({mediaType:t.tagName.toLowerCase(),duration:t.duration||0},i?{goalTarget:i}:{}),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("play",e),this.conversionListeners.set("play",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("play",e)})))}setupCustomEventTracking(){const e=e=>{if(!this.experimentId||!this.assignment)return;const t=e.detail;this.manager.trackConversion(this.experimentId,this.assignment.variantId,t.type||"conversions",Object.assign(Object.assign({},t),{timestamp:Date.now()}))};this.shadowRoot&&(this.shadowRoot.addEventListener("widgetic:conversion",e),this.conversionListeners.set("conversion",(()=>{var t;null===(t=this.shadowRoot)||void 0===t||t.removeEventListener("widgetic:conversion",e)})))}sendGoalToWidget(e){var t;if(this.experimentId&&this.assignment)try{const i=this.manager.getPrimaryMetric(this.experimentId);if(!i)return;null===(t=o(e))||void 0===t||t.sendAbGoal({metric:i,goalTarget:this.assignment.goalTarget||null})}catch(e){O.warn("Failed to tell the widget its A/B test goal",{experimentId:this.experimentId,error:e})}}setupGoalListeners(){if(!this.shadowRoot||this.conversionListeners.has("goal"))return;const e=this.shadowRoot,t=e=>{var t;if(!this.experimentId||!this.assignment)return;const i=null===(t=e.detail)||void 0===t?void 0:t.capabilities,n=Array.isArray(i)&&i.includes(u);this.manager.setWidgetReportsGoals(this.experimentId,n),this.assignment.goalTarget&&!n&&O.warn("This widget cannot report which element was used: the goal counts any use of its metric",{experimentId:this.experimentId,goalTarget:this.assignment.goalTarget}),this.sendGoalToWidget(e.target)},i=e=>{if(!this.experimentId||!this.assignment)return;const t=e.detail||{},i=t.metric||this.manager.getPrimaryMetric(this.experimentId);i&&this.manager.trackConversion(this.experimentId,this.assignment.variantId,i,{goalTarget:t.goalTarget,timestamp:Date.now()})},n=e=>t=>{var i;if(!this.experimentId||!this.assignment)return;const n=null===(i=t.detail)||void 0===i?void 0:i.type;"clicks"===e&&void 0!==n&&"click"!==n||this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,{timestamp:Date.now()})},s=n("clicks"),a=n("submissions"),r=n("plays");e.addEventListener("widgetic:ready",t),e.addEventListener("widgetic:goal",i),e.addEventListener("widgetic:interaction",s),e.addEventListener("widgetic:form-submit",a),e.addEventListener("widgetic:media:play",r),this.conversionListeners.set("goal",(()=>{e.removeEventListener("widgetic:ready",t),e.removeEventListener("widgetic:goal",i),e.removeEventListener("widgetic:interaction",s),e.removeEventListener("widgetic:form-submit",a),e.removeEventListener("widgetic:media:play",r)}))}isClickableElement(e){return["BUTTON","A","INPUT"].includes(e.tagName)||e.hasAttribute("onclick")||e.hasAttribute("data-click-track")||"INPUT"===e.tagName&&["button","submit"].includes(e.type)||"button"===e.getAttribute("role")}trackImpression(){return U(this,void 0,void 0,(function*(){if(!this.impressionTracked&&this.experimentId&&this.assignment)try{const e={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0};yield this.manager.trackImpression(this.experimentId,this.assignment.variantId,e),this.impressionTracked=!0,this.analyticsTracker.trackCompositionView({experiment_id:this.experimentId,variant_id:this.assignment.variantId,composition_id:this.assignment.compositionId}),O.debug("Impression tracked",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){O.error("Failed to track impression",{experimentId:this.experimentId,error:e})}}))}handleConversionEvent(e){this.dispatchEvent(new CustomEvent("conversion",{detail:e,bubbles:!0})),this.analyticsTracker.trackCompositionInteraction({interactionType:"click",elementType:"ab_test_conversion",elementId:e.experimentId,coordinates:{x:0,y:0},duration:0})}onWidgetReady(e){var t,i;O.debug("Widget ready for A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,widgetId:e.widgetId}),this.dispatchEvent(new CustomEvent("widget-ready",{detail:{experimentId:this.experimentId,variantId:null===(i=this.assignment)||void 0===i?void 0:i.variantId,widgetId:e.widgetId},bubbles:!0}))}onWidgetError(e){var t;O.error("Widget error in A/B test",{experimentId:this.experimentId,variantId:null===(t=this.assignment)||void 0===t?void 0:t.variantId,error:e.details}),this.renderError("Widget failed to load")}renderLoading(){this.shadowRoot&&(this.shadowRoot.innerHTML='\n <style>\n .ab-test-loading {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #666;\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n }\n .spinner {\n width: 20px;\n height: 20px;\n border: 2px solid #e0e0e0;\n border-top: 2px solid #007cba;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin-right: 10px;\n }\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n <div class="ab-test-loading">\n <div class="spinner"></div>\n Loading test...\n </div>\n ')}renderError(e){this.shadowRoot&&(this.shadowRoot.innerHTML=`\n <style>\n .ab-test-error {\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100px;\n color: #d32f2f;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n background-color: #ffebee;\n border: 1px solid #ffcdd2;\n border-radius: 4px;\n padding: 16px;\n text-align: center;\n }\n </style>\n <div class="ab-test-error">\n ${e}\n </div>\n `,this.dispatchEvent(new CustomEvent("error",{detail:{message:e},bubbles:!0})))}cleanup(){if(this.conversionListeners.forEach((e=>e())),this.conversionListeners.clear(),this.widgetInstance)try{this.widgetManager.unregisterWidget(this.widgetInstance.id)}catch(e){O.warn("Failed to cleanup widget instance",{error:e})}this.impressionTracked=!1,this.assignment=null,this.widgetInstance=null}trackConversion(e="custom",t){return this.experimentId&&this.assignment?this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,t):Promise.reject(new Error("A/B test not initialized"))}getAssignment(){return this.assignment?Object.assign({},this.assignment):null}getExperimentId(){return this.experimentId}static register(){"undefined"!=typeof window&&window.customElements&&(customElements.get("widgetic-abtest")||customElements.define("widgetic-abtest",Y))}}Y.register();const J="undefined"!=typeof HTMLElement?HTMLElement:class{};class X extends J{constructor(){super(),this.widgetInstance=null,this.isInitialized=!1,this.retryCount=0,this.maxRetries=3,this.retryDelay=1e3,this.experimentId=null,this.selectedLanguage=null,this.translationData=null,this.widgetManager=v(),T.debug("[TranslationElement] Created translation element")}connectedCallback(){if(this.isInitialized)T.debug("[TranslationElement] Already initialized, skipping");else{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return T.error("[TranslationElement] Missing experiment-id attribute"),void this.displayError("Missing experiment-id attribute");T.debug(`[TranslationElement] Connected with experiment ID: ${this.experimentId}`),this.initializeTranslation()}}disconnectedCallback(){T.debug("[TranslationElement] Disconnected"),this.cleanup()}initializeTranslation(){return U(this,void 0,void 0,(function*(){try{this.isInitialized=!0;const e=this.detectBrowserLanguages();if(T.debug("[TranslationElement] Detected user languages:",e),this.translationData=yield this.fetchTranslationExperiment(this.experimentId),!this.translationData)throw new Error("Failed to fetch translation experiment data");this.selectedLanguage=this.findBestLanguageMatch(e,this.translationData),T.debug("[TranslationElement] Selected language:",this.selectedLanguage);const t=this.getCompositionForLanguage(this.selectedLanguage);if(!t)throw new Error(`No composition found for language: ${this.selectedLanguage}`);yield this.loadWidget(t),T.info("[TranslationElement] Translation experiment loaded successfully",{experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,compositionId:t})}catch(e){T.error("[TranslationElement] Failed to initialize translation:",e),yield this.handleInitializationError(e)}}))}detectBrowserLanguages(){var e;const t=navigator.language.toLowerCase(),i=((null===(e=navigator.languages)||void 0===e?void 0:e.map((e=>e.toLowerCase())))||[t]).flatMap((e=>{const t=[e];return e.includes("-")&&t.push(e.split("-")[0]),t}));return[...new Set(i)]}fetchTranslationExperiment(e){return U(this,void 0,void 0,(function*(){try{const t=W(),i=new D({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new N(i),s=yield n.getTranslationConfig({id:e});return(null==s?void 0:s.data)||null}catch(e){throw T.error("[TranslationElement] Error fetching translation experiment:",e),e}}))}findBestLanguageMatch(e,t){const i=Object.keys(t.languageCompositions||{}),n=t.rootLanguage||"en";T.debug("[TranslationElement] Available languages:",i),T.debug("[TranslationElement] Root language:",n);for(const t of e)if(i.includes(t))return T.debug("[TranslationElement] Found exact match:",t),t;for(const t of e){const e=t.split("-")[0],n=i.find((t=>t.startsWith(e+"-")||t===e));if(n)return T.debug("[TranslationElement] Found base language match:",n),this.trackFallbackUsage(t,n,"language_family").catch((e=>{T.debug("[TranslationElement] Failed to track language family fallback:",e)})),n}T.debug("[TranslationElement] No matches found, falling back to root language:",n);const s=e[0]||"unknown";return this.trackFallbackUsage(s,n,"root_fallback").catch((e=>{T.debug("[TranslationElement] Failed to track root fallback:",e)})),n}getCompositionForLanguage(e){if(!this.translationData)return null;if(e===this.translationData.rootLanguage)return this.translationData.rootCompositionId;return(this.translationData.languageCompositions||{})[e]||this.translationData.rootCompositionId}loadWidget(e){return U(this,void 0,void 0,(function*(){const t=V(e),i={compositionId:e,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};this.widgetInstance=yield this.widgetManager.registerWidget(t,i,this),this.trackTranslationView()}))}trackTranslationView(){try{const e={experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,userLanguages:this.detectBrowserLanguages(),timestamp:(new Date).toISOString(),userAgent:navigator.userAgent,referrer:document.referrer,url:window.location.href};this.sendAnalytics(e).catch((e=>{T.warn("[TranslationElement] Failed to send analytics:",e)}))}catch(e){T.warn("[TranslationElement] Error in analytics tracking:",e)}}sendAnalytics(e){return U(this,void 0,void 0,(function*(){try{const t=W(),i=new D({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new N(i);yield n.submitTranslationAnalyticsEvent({id:this.experimentId,submitTranslationAnalyticsEventRequest:e})}catch(e){T.debug("[TranslationElement] Analytics request failed:",e)}}))}trackFallbackUsage(e,t,i){return U(this,void 0,void 0,(function*(){try{const n={eventType:"fallback_used",language:t,compositionId:this.getCompositionForLanguage(t)||"",metadata:{requestedLanguage:e,selectedLanguage:t,fallbackType:i,userAgent:navigator.userAgent,timestamp:(new Date).toISOString()},timestamp:(new Date).toISOString()};yield this.sendAnalytics(n),T.debug("[TranslationElement] Fallback usage tracked:",{requested:e,selected:t,fallbackType:i})}catch(e){T.debug("[TranslationElement] Failed to track fallback usage:",e)}}))}handleInitializationError(e){return U(this,void 0,void 0,(function*(){if(this.retryCount<this.maxRetries){this.retryCount++,T.warn(`[TranslationElement] Retrying initialization (${this.retryCount}/${this.maxRetries}):`,e.message),yield new Promise((e=>setTimeout(e,this.retryDelay*this.retryCount)));try{return void(yield this.initializeTranslation())}catch(e){T.error("[TranslationElement] Retry failed:",e)}}this.displayError(`Translation loading failed: ${e.message}`)}))}displayError(e){this.innerHTML=`\n <div style="\n padding: 1rem;\n border: 1px solid #ef4444;\n border-radius: 0.5rem;\n background-color: #fef2f2;\n color: #dc2626;\n font-family: system-ui, -apple-system, sans-serif;\n font-size: 0.875rem;\n margin: 1rem 0;\n ">\n <strong>Translation Error:</strong> ${e}\n </div>\n `}cleanup(){this.widgetInstance&&(this.widgetManager.unregisterWidget(this.widgetInstance.id),this.widgetInstance=null),this.isInitialized=!1,this.retryCount=0}switchLanguage(e){if(!this.translationData)throw new Error("Translation data not loaded");const t=this.getCompositionForLanguage(e);if(!t)throw new Error(`No composition found for language: ${e}`);return this.cleanup(),this.selectedLanguage=e,this.loadWidget(t)}getSelectedLanguage(){return this.selectedLanguage}getAvailableLanguages(){return this.translationData?Object.keys(this.translationData.languageCompositions||{}):[]}static register(){try{"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-translations")||(customElements.define("widgetic-translations",X),T.info("[TranslationElement] Custom element registered")))}catch(e){T.error("[TranslationElement] Failed to register custom element:",e)}}}X.register();const Z=w();"undefined"!=typeof window&&"undefined"!=typeof customElements&&(P(),Y.register(),X.register()),"undefined"!=typeof window&&(window.WidgeticEmbedSDK=Z,window.Widgetic={SDK:Z,getSDK:w,EmbedSDK:y,config:{API_URL:z.API_URL,API_VERSION:z.API_VERSION,CLIENT_URL:z.CLIENT_URL,PRODUCTION_URL:z.PRODUCTION_URL,NODE_ENV:z.NODE_ENV},log:T,WidgeticWidget:Q,registerWidgeticWidget:P,cssDebugger:b,enableCSSDebug:()=>b.enableDebugMode(),disableCSSDebug:()=>b.disableDebugMode(),analyzeWidget:e=>b.analyzeWidget(e),ABTestManager:q,ABTestElement:Y,TranslationElement:X});export{Y as ABTestElement,q as ABTestManager,y as EmbedSDK,X as TranslationElement,y as WidgeticEmbedSDK,Q as WidgeticWidget,z as config,b as cssDebugger,Z as default,V as generateInstanceId,x as getAuthToken,w as getSDK,T as log,P as registerWidgeticWidget};