@widgetic/embed-sdk 2.0.17 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -4
- package/dist/browser/chunks/ABTestManager.js +1 -1
- package/dist/browser/chunks/api.js +1 -1
- package/dist/browser/chunks/core.js +1 -1
- package/dist/browser/chunks/renderers.js +1 -1
- package/dist/browser/chunks/scanner.js +1 -1
- package/dist/browser/chunks/workflows.js +1 -0
- package/dist/browser/embed-bootstrap.js +1 -1
- package/dist/browser/embed-sdk.js +1 -1
- package/dist/esm/chunks/ABTestManager.js +1 -1
- package/dist/esm/chunks/api.js +1 -1
- package/dist/esm/chunks/core.js +1 -1
- package/dist/esm/chunks/renderers.js +1 -1
- package/dist/esm/chunks/scanner.js +1 -1
- package/dist/esm/chunks/workflows.js +1 -0
- package/dist/esm/embed-bootstrap.js +1 -1
- package/dist/esm/embed-sdk.js +1 -1
- package/dist/esm/types/abTesting/abVisitor.d.ts +2 -0
- package/dist/esm/types/core/autoscale-manager.d.ts +6 -0
- package/dist/esm/types/embed-sdk.d.ts +1 -0
- package/dist/esm/types/sdk/embed-sdk.d.ts +1 -0
- package/dist/esm/types/utils/declarative-embed-parser.d.ts +5 -0
- package/dist/esm/types/utils/host-bridge-snapshot.d.ts +34 -1
- package/dist/esm/types/utils/host-workflow-watch.d.ts +62 -0
- package/dist/esm/types/utils/hydrate-published-host.d.ts +1 -0
- package/dist/esm/types/utils/mount-direct-widget.d.ts +19 -0
- package/dist/esm/types/utils/public-embed-lookup.d.ts +16 -0
- package/dist/esm/types/utils/published-host-bridge.d.ts +21 -3
- package/dist/esm/types/utils/workflow-code-loader.d.ts +14 -0
- package/dist/esm/types/utils/workflow-code-loader.umd.d.ts +32 -0
- package/dist/esm/types/utils/workflow-embed-registry.d.ts +15 -0
- package/dist/esm/types/utils/workflow-page-events.d.ts +41 -0
- package/dist/esm/types/utils/workflow-shared-contract.d.ts +35 -0
- package/dist/esm/types/utils/workflow-shared-services.d.ts +84 -0
- package/dist/esm/types/workflows/umd-entry.d.ts +1 -0
- package/dist/esm/types/workflows/visitor-position.d.ts +32 -0
- package/dist/esm/types/workflows/workflow-autoscale.d.ts +41 -0
- package/dist/esm/types/workflows/workflow-counts.d.ts +65 -0
- package/dist/esm/types/workflows/workflow-host.d.ts +71 -0
- package/dist/esm/types/workflows/workflow-lookup.d.ts +53 -0
- package/dist/esm/types/workflows/workflow-signals.d.ts +34 -0
- package/dist/esm/types/workflows/workflow-stage.d.ts +154 -0
- package/dist/umd/embed-bootstrap.js +1 -1
- package/dist/umd/embed-sdk-workflows.js +1 -0
- package/dist/umd/embed-sdk.js +1 -1
- package/package.json +2 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
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(){return"undefined"==typeof window?{customElements:!1,http3:!1,resizeObserver:!1,fullscreenApi:!1,popupBlocking:!1}:{customElements:"undefined"!=typeof customElements&&"function"==typeof customElements.define,http3:st(),resizeObserver:"undefined"!=typeof ResizeObserver,fullscreenApi:ct(),popupBlocking:ut()}}function st(){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 ct(){return!("undefined"==typeof document||!document.documentElement)&&!!(document.documentElement.requestFullscreen||document.documentElement.webkitRequestFullscreen||document.documentElement.mozRequestFullScreen||document.documentElement.msRequestFullscreen)}function ut(){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 lt(t,e){switch(t){case"custom-element":case"auto":default:return e.customElements?"custom-element":"iframe";case"iframe":return"iframe"}}function dt(){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 pt=Object.freeze({__proto__:null,checkSdkInitialization:function(){if("undefined"==typeof window)return!1;const t="widgetic-sdk-initialized";return dt()?!!localStorage.getItem(t)||(localStorage.setItem(t,Date.now().toString()),!1):!!window.__widgeticInitialized},clearSdkInitialization:function(){dt()&&localStorage.removeItem("widgetic-sdk-initialized"),delete window.__widgeticInitialized},detectBrowserCapabilities:at,determineBestRenderMode:lt,hasIntersectionObserver:function(){return"undefined"!=typeof IntersectionObserver},isLocalStorageAvailable:dt});class gt{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 bt(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 ft=Object.freeze({__proto__:null,WidgetMetadataAnalyzer:gt,analyzeWidgetRequirementsEnhanced:function(t){const e=new Set;for(const i of t){const t=gt.analyzeElement(i);if(t){bt(t).forEach((t=>e.add(t)))}}return Array.from(e)},getRequiredChunks:bt});export{e as D,r as M,et as a,F as b,Q as c,i as d,at as e,O as f,D as g,rt as h,_ as i,lt as j,C as k,dt as l,it as m,L as n,ot as o,n as p,pt as q,ft 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:k(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 k(t){const e=t.getAttribute("autoscale");return!!e&&(("true"===e||""===e||"false"!==e)&&(S(t)||!0))}function S(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","workflow-id","autoscale-min-height","autoscale-max-height","autoscale-debounce","autoscale-threshold","autoscale-animate","autoscale-animation-duration","adaptive","responsive","theme","mode","colors","context","values","media-resolver","mediaresolver","sandbox","autoload","use-iframe","embed-target","event-trigger","trigger-delay","trigger-scroll-distance","overlay-position","overlay-full-width","overlay-backdrop","max-views","time-period","device-mobile-enabled","device-desktop-enabled","display-on-mobile","display-on-desktop","use-breakpoints","mobile-breakpoint","tablet-breakpoint","desktop-breakpoint","design","content","items","content-items","contentitems"]),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){return Array.from(t.children).filter((t=>!H(t)))}function V(t){const e=t.toLowerCase();return!!q.has(e)||(!!e.startsWith("data-widgetic-")||(!!e.startsWith("aria-")||!!e.startsWith("on")))}function J(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 U(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 X(t){if(!t||!t.trim())return null;try{const e=JSON.parse(t);if(Array.isArray(e))return U(e)}catch(t){}return null}function Y(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 Z(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&&Y(e.properties,i,!0);t.properties&&Y(t.properties,i,!0)}}}if(Array.isArray(t.propertyGroups)){r=!0;for(const e of t.propertyGroups)e&&"object"==typeof e&&Y(e.properties,i,!0)}if(t.properties&&Y(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 K=new Set(["$schema","id","name","version","contentType","genericContent","contentItems","contentItemsSnapshot","items","options","componentGroups","propertyGroups"]);function Q(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(!Y(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&&Y(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=U(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&&(K.has(i)||"properties"===i)||(!n||"options"!==i&&"contentType"!==i&&"$schema"!==i)&&(e[i]=o));return i}function tt(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]=J(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 et(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 it(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=U(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){Z(c,r);continue}if("content"===u){const t=Q(c,n);t&&t.length>0&&(o=t);continue}let l=!1;if(c.design&&"object"==typeof c.design&&!Array.isArray(c.design)&&(Z(c.design,r),l=!0),(Array.isArray(c.componentGroups)||Array.isArray(c.propertyGroups))&&(Z(c,r),l=!0),c.content&&"object"==typeof c.content&&!Array.isArray(c.content)){const t=Q(c.content,n);t&&t.length>0&&(o=t),l=!0}if(c.values&&"object"==typeof c.values&&!Array.isArray(c.values)){const t=Q(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=Q(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=et(null==e?void 0:e.content,t),a=et(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=$(t.getAttribute("design"));a&&Z(a,r);const s=$(t.getAttribute("content"));if(s){const t=Q(s,n);t&&t.length>0&&(o=t)}const c=$(t.getAttribute("values"));if(c){const t=Q(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[et(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[et(null==e?void 0:e.content,r)||r]=J(i.value)}continue}if(V(t))continue;const a=W(t);if(!a||a in Object.prototype)continue;const s=et(null==e?void 0:e.content,a),c=et(null==e?void 0:e.design,a);if(s&&!c)n[s]=J(i.value);else if(c&&!s)r[c]=i.value;else{r[a]=i.value,n[a]=J(i.value);const e=t.replace(/^data-/,"");e===a||e in Object.prototype||(r[e]=i.value)}}let u=tt(t);if(0===u.length){const e=X(t.getAttribute("content-items"))||X(t.getAttribute("contentitems"))||X(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 rt(t,e){const i=null!=e?e:{},r=it(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 nt(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 ot=new WeakMap;function at(t,e,i){const r=ot.get(t);r&&r();const n="undefined"!=typeof MutationObserver?MutationObserver:null;if(!n)return()=>{};let o,a=!1;try{o=new n((r=>{nt(r)&&(a||(a=!0,queueMicrotask((()=>{a=!1;const r=it(t,e);i(r)}))))}))}catch(t){return()=>{}}o.observe(t,{attributes:!0,childList:!0,subtree:!0,characterData:!0});const s=()=>{o.disconnect(),ot.delete(t)};return ot.set(t,s),s}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,it as a,F as b,tt as c,i as d,st as e,O as f,D as g,nt as h,_ as i,dt as j,C as k,pt as l,rt as m,V as n,at as o,n as p,B as q,L as r,gt as s,mt as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{_ as t}from"./vendor.js";import{s as e,d as i,O as o,r as s,P as n,b as r,R as d,W as a,c as l,e as u,w as c,f as h,h as f,i as p}from"./api.js";import{r as m,l as g,q as v,w,t as b}from"./core.js";import{p as y,h as I,w as k,a as T}from"./renderers.js";import{n as A,q as E}from"./scanner.js";import"./media.js";import"./messaging.js";import"./advanced.js";import"./display.js";import"./performance.js";import"./security.js";const S=/^[A-Za-z0-9_-]{1,64}$/;function O(t){const e=new Map;for(const i of t.nodes)e.has(i.id)||e.set(i.id,i);const i=new Map,o=new Map;for(const e of t.edges)C(i,e.source,e),C(o,e.target,e);return{graph:t,nodesById:e,outgoingBySource:i,incomingByTarget:o}}function C(t,e,i){const o=t.get(e);o?o.push(i):t.set(e,[i])}function N(t,e){return t.outgoingBySource.get(e)??[]}function H(t){return"composition"===t?.type}function $(t){return"condition"===t?.type}function W(t,e){const i=[];for(const s of N(t,e)){const e=t.nodesById.get(s.target);o=e,"trigger"===o?.type&&i.push(e)}var o;return i}function M(t,e,i){return N(t,e).find((t=>t.sourcePort===i))}const R={text:["is","isNot","contains","doesNotContain","startsWith","endsWith","isEmpty","isNotEmpty"],number:["is","isNot","greaterThan","atLeast","lessThan","atMost","isEmpty","isNotEmpty"],boolean:["is","isNot"]},L=["is","isNot","contains","doesNotContain","startsWith","endsWith","greaterThan","atLeast","lessThan","atMost","isEmpty","isNotEmpty"];function P(t){return null==t||"string"==typeof t&&""===t.trim()}function x(t){return null==t?"":String(t).trim().toLowerCase()}function j(t){if("number"==typeof t)return Number.isFinite(t)?t:void 0;if("string"==typeof t){const e=t.trim();if(""===e)return;const i=Number(e);return Number.isFinite(i)?i:void 0}}const F=new Set(["true","yes","1","on"]),B=new Set(["false","no","0","off"]);function _(t){if("boolean"==typeof t)return t;if("number"==typeof t)return 1===t||0!==t&&void 0;if("string"==typeof t){const e=t.trim().toLowerCase();if(F.has(e))return!0;if(B.has(e))return!1}}function z(t,e){const{operator:i}=t;if("isEmpty"===i)return P(e);if("isNotEmpty"===i)return!P(e);if(!function(t,e){return R[e].includes(t)}(i,t.field.type))return!1;switch(t.field.type){case"number":return function(t,e,i){const o=j(e),s=j(i);if("isNot"===t)return void 0===o||void 0===s||o!==s;if(void 0===o||void 0===s)return!1;switch(t){case"is":return o===s;case"greaterThan":return o>s;case"atLeast":return o>=s;case"lessThan":return o<s;case"atMost":return o<=s;default:return!1}}(i,e,t.value);case"boolean":return function(t,e,i){const o=_(e),s=_(i),n=void 0!==o&&void 0!==s&&o===s;return"is"===t?n:"isNot"===t&&!n}(i,e,t.value);default:return function(t,e,i){const o=x(e),s=x(i),n=P(e);switch(t){case"is":return!n&&o===s;case"isNot":return n||o!==s;case"contains":return!n&&""!==s&&o.includes(s);case"doesNotContain":return n||""===s||!o.includes(s);case"startsWith":return!n&&""!==s&&o.startsWith(s);case"endsWith":return!n&&""!==s&&o.endsWith(s);default:return!1}}(i,e,t.value)}}function D(t,e){if(0===t.tests.length)return!1;const i=t=>z(t,e(t.field));return"any"===t.match?t.tests.some(i):t.tests.every(i)}const U={seconds:1e3,minutes:6e4,hours:36e5,days:864e5,weeks:6048e5},V=["seconds","minutes","hours","days","weeks"],q=365*U.days;function Z(t){return"string"==typeof t&&V.includes(t)}function G(t,e){if("after"===t.mode){const i=function(t,e){if("number"!=typeof t||!Number.isInteger(t)||t<1)return;if(!Z(e))return;const i=t*U[e];return i<=q?i:void 0}(t.amount,t.unit);if(void 0===i||!Number.isFinite(e))return;return e+i}if("at"===t.mode){const e=Date.parse(t.at);return Number.isFinite(e)?e:void 0}}function J(t,e,i){const o=G(t,e);return void 0===o?void 0:Math.max(0,o-i)}function K(t,e){const i=t.trigger;switch(e.type){case"input":return"input"===i.kind&&i.table===e.table;case"action":return"action"===i.kind&&i.actionId===e.actionId;case"pageEvent":return"pageEvent"===i.kind&&i.name===e.name;case"scheduled":return"scheduled"===i.kind&&t.id===e.triggerId;default:return!1}}function Q(t,e,i){const o=[e.id],s=[],n=function(t){const e="input"===t.type||"pageEvent"===t.type?t.values:void 0,i="input"===t.type?"input":"pageEvent"===t.type?"event":void 0;return t=>{if(e&&t.kind===i)return Object.prototype.hasOwnProperty.call(e,t.name)?e[t.name]:void 0}}(i);let r=M(t,e.id,"out");for(let e=0;e<=25&&r;e+=1){s.push(r.id);const e=t.nodesById.get(r.target);if(H(e))return{destination:e,passedNodeIds:o,takenEdgeIds:s};if(!$(e))break;o.push(e.id);const i=e.cases.find((t=>D(t,n)));r=M(t,e.id,i?i.id:"default")}return{passedNodeIds:o,takenEdgeIds:s}}function X(t,e,i,o={}){const s=o.index??O(t),n=s.nodesById.get(e.nodeId);if(!H(n))return{outcome:"ignored",reason:"unknown_position"};const r=[];for(const t of W(s,n.id)){if(!K(t,i))continue;r.push(t.id);const e=Q(s,t,i);if(e.destination&&e.destination.id!==n.id)return{outcome:"moved",position:{nodeId:e.destination.id},firedTriggerId:t.id,passedNodeIds:e.passedNodeIds,takenEdgeIds:e.takenEdgeIds}}return r.length>0?{outcome:"stayed",firedTriggerIds:r}:{outcome:"ignored",reason:"no_matching_trigger"}}function Y(t,e,i){t.some((t=>i(t,e)))||t.push(e)}function tt(t,e,i,o){const s=[],n=M(t,e,"out");n&&s.push(n.target);const r=new Set;for(;s.length>0;){const e=s.pop();if(r.has(e))continue;r.add(e);const n=t.nodesById.get(e);if($(n)){for(const t of n.cases)for(const e of t.tests)"input"===e.field.kind&&Y(o,{table:i,column:e.field.name},((t,e)=>t.table===e.table&&t.column===e.column));for(const i of N(t,e))s.push(i.target)}}}function et(t,e,i={}){const o=i.index??O(t),s={inputTables:[],inputColumns:[],actionIds:[],pageEventNames:[],schedules:[]},n=(t,e)=>t===e;for(const t of W(o,e)){const e=t.trigger;switch(e.kind){case"input":if(""===e.table)break;Y(s.inputTables,e.table,n),tt(o,t.id,e.table,s.inputColumns);break;case"action":""!==e.actionId&&Y(s.actionIds,e.actionId,n);break;case"pageEvent":""!==e.name&&Y(s.pageEventNames,e.name,n);break;case"scheduled":s.schedules.push({triggerId:t.id,schedule:e.schedule})}}return s}class it{issues=[];report(t,e){this.issues.push({code:t,severity:"error",detail:e})}}function ot(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function st(t){return"string"==typeof t&&S.test(t)?t:void 0}function nt(t,e=200){return"string"==typeof t&&t.length<=e?t:void 0}function rt(t){return"text"===t||"number"===t||"boolean"===t?t:void 0}function dt(t,e,i){if(!ot(t))return void i.report("malformed",e);const o=function(t,e,i){if(!ot(t))return void i.report("malformed",e);const o="input"===t.kind||"event"===t.kind?t.kind:void 0,s=nt(t.name,64),n=rt(t.type);if(o&&void 0!==s&&n)return{kind:o,name:s,type:n};i.report("malformed",e)}(t.field,`${e}.field`,i),s=function(t){return"string"==typeof t&&L.includes(t)?t:void 0}(t.operator);let n;return s||i.report("malformed",`${e}.operator`),void 0!==t.value&&(n=function(t){return null===t||"boolean"==typeof t?t:"number"==typeof t?Number.isFinite(t)?t:void 0:nt(t)}(t.value),void 0===n&&i.report("malformed",`${e}.value`)),o&&s?void 0===n?{field:o,operator:s}:{field:o,operator:s,value:n}:void 0}function at(t,e,i){if(ot(t))switch(t.kind){case"input":{const o=nt(t.table);return void 0===o&&i.report("malformed",`${e}.table`),void 0===o?void 0:{kind:"input",table:o}}case"action":{const o=nt(t.actionId);return void 0===o&&i.report("malformed",`${e}.actionId`),void 0===o?void 0:{kind:"action",actionId:o}}case"pageEvent":{const o=nt(t.name,64);void 0===o&&i.report("malformed",`${e}.name`);const s=function(t,e,i){if(!Array.isArray(t)||t.length>100)return void i.report("malformed",e);const o=[];return t.forEach(((t,s)=>{const n=ot(t)?nt(t.name,64):void 0,r=ot(t)?rt(t.type):void 0;void 0!==n&&r?o.push({name:n,type:r}):i.report("malformed",`${e}[${s}]`)})),o}(t.values,`${e}.values`,i);return void 0!==o&&s?{kind:"pageEvent",name:o,values:s}:void 0}case"scheduled":{const o=function(t,e,i){if(ot(t)&&"after"===t.mode&&"number"==typeof t.amount&&Z(t.unit)&&Number.isFinite(t.amount))return{mode:"after",amount:t.amount,unit:t.unit};if(ot(t)&&"at"===t.mode){const e=nt(t.at,64);if(void 0!==e)return{mode:"at",at:e}}i.report("malformed",e)}(t.schedule,`${e}.schedule`,i);return o?{kind:"scheduled",schedule:o}:void 0}default:return void i.report("unknown_trigger_kind",`${e}.kind`)}else i.report("malformed",e)}function lt(t,e,i){if(!ot(t))return void i.report("malformed",e);const o=st(t.id);o||i.report("bad_id",`${e}.id`);const s=function(t){if(void 0!==t)return ot(t)&&"number"==typeof t.x&&"number"==typeof t.y&&Number.isFinite(t.x)&&Number.isFinite(t.y)?{x:t.x,y:t.y}:"invalid"}(t.position);"invalid"===s&&i.report("malformed",`${e}.position`);const n=o&&"invalid"!==s?s?{id:o,position:s}:{id:o}:void 0;switch(t.type){case"composition":{const o=nt(t.compositionId,200);if(void 0===o&&i.report("malformed",`${e}.compositionId`),void 0!==t.startsHere&&"boolean"!=typeof t.startsHere)return void i.report("malformed",`${e}.startsHere`);if(!n||void 0===o)return;return!0===t.startsHere?{...n,type:"composition",compositionId:o,startsHere:!0}:{...n,type:"composition",compositionId:o}}case"trigger":{const o=at(t.trigger,`${e}.trigger`,i);return n&&o?{...n,type:"trigger",trigger:o}:void 0}case"condition":{if(!Array.isArray(t.cases)||t.cases.length>100)return void i.report("malformed",`${e}.cases`);const o=[];return t.cases.forEach(((t,s)=>{const n=function(t,e,i){if(!ot(t)||!Array.isArray(t.tests)||t.tests.length>100)return void i.report("malformed",e);const o=st(t.id),s="all"===t.match||"any"===t.match?t.match:void 0;let n;o||i.report("bad_id",`${e}.id`),s||i.report("malformed",`${e}.match`),void 0!==t.label&&(n=nt(t.label),void 0===n&&i.report("malformed",`${e}.label`));const r=[];return t.tests.forEach(((t,o)=>{const s=dt(t,`${e}.tests[${o}]`,i);s&&r.push(s)})),o&&s?void 0===n?{id:o,match:s,tests:r}:{id:o,label:n,match:s,tests:r}:void 0}(t,`${e}.cases[${s}]`,i);n&&o.push(n)})),n?{...n,type:"condition",cases:o}:void 0}default:return void i.report("unknown_node_type",`${e}.type`)}}function ut(t){const e=new it;if(!ot(t))return e.report("malformed","graph"),{issues:e.issues};if(1!==t.schemaVersion)return e.report("schema_version","schemaVersion"),{issues:e.issues};if(!Array.isArray(t.nodes)||!Array.isArray(t.edges))return e.report("malformed","nodes/edges"),{issues:e.issues};if(t.nodes.length>100||t.edges.length>300)return e.report("graph_too_large","nodes/edges"),{issues:e.issues};const i=[];t.nodes.forEach(((t,o)=>{const s=lt(t,`nodes[${o}]`,e);s&&i.push(s)}));const o=[];return t.edges.forEach(((t,i)=>{const s=function(t,e,i){if(!ot(t))return void i.report("malformed",e);const o=st(t.id),s=st(t.source),n=st(t.sourcePort),r=st(t.target);return o||i.report("bad_id",`${e}.id`),s&&n&&r||i.report("malformed",e),o&&s&&n&&r?{id:o,source:s,sourcePort:n,target:r}:void 0}(t,`edges[${i}]`,e);s&&o.push(s)})),e.issues.length>0?{issues:e.issues}:{graph:{schemaVersion:1,nodes:i,edges:o},issues:[]}}const ct=/^[A-Za-z0-9_.:-]{1,128}$/;function ht(t){return`widgetic_workflow_${t}`}function ft(t){return"string"==typeof t&&ct.test(t)}function pt(t){return"number"==typeof t&&Number.isFinite(t)&&t>=0}function mt(t,e){try{w(ht(t),JSON.stringify({v:1,versionId:e.versionId,nodeId:e.nodeId,compositionId:e.compositionId,startedAt:e.startedAt,reachedAt:e.reachedAt}))}catch(e){g.debug("[workflows] The visitor's position could not be kept",{workflowId:t,error:e})}}function gt(t){v(ht(t))}const vt=/^[A-Za-z0-9_-]{1,64}$/,wt=new Set(["n","e","f"]);class bt{constructor(t){this.pending=[],this.lastEventOf=new Map,this.flushTimer=null,this.stopped=!1,this.listening=!1,this.onPageHide=()=>{this.flushBeforeLeaving()},this.onVisibilityChange=()=>{"hidden"===document.visibilityState&&this.flushBeforeLeaving()},this.options=t}isStopped(){return this.stopped}start(){this.listening||this.stopped||(this.listening=!0,window.addEventListener("pagehide",this.onPageHide),document.addEventListener("visibilitychange",this.onVisibilityChange))}count(t,e,i=1){if(this.stopped||!this.options.token)return;if(!wt.has(t)||!vt.test(e)||!Number.isInteger(i)||i<1)return;const o=`${t}:${e}`;let s=i;for(;s>0;){let i=this.lastEventOf.get(o);(!i||i.c>=50)&&(i={k:t,id:e,c:0},this.pending.push(i),this.lastEventOf.set(o,i));const n=Math.min(s,50-i.c);i.c+=n,s-=n}this.pending.length>=100?this.flush():null===this.flushTimer&&(this.flushTimer=setTimeout((()=>this.flush()),2e3))}flushBeforeLeaving(){if(!this.stopped&&this.options.token)for(;this.pending.length>0;){const t=this.takeBatch();if(!this.options.isActive())return void this.forgetPending();this.sendWithBeacon(t)}}dispose(){this.stopped=!0,this.forgetPending(),this.listening&&(window.removeEventListener("pagehide",this.onPageHide),document.removeEventListener("visibilitychange",this.onVisibilityChange),this.listening=!1)}takeBatch(){const t=this.pending.splice(0,100);for(const e of t){const t=`${e.k}:${e.id}`;this.lastEventOf.get(t)===e&&this.lastEventOf.delete(t)}return t}forgetPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.pending=[],this.lastEventOf.clear()}flush(){if(null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.stopped||0===this.pending.length)return;if(!this.options.isActive())return void this.forgetPending();const t=this.takeBatch();this.sendWithRequest(t),this.pending.length>0&&null===this.flushTimer&&(this.flushTimer=setTimeout((()=>this.flush()),2e3))}reportAddress(){return`${this.options.apiOrigin}/embed/workflows/${encodeURIComponent(this.options.workflowId)}/events`}reportBody(t){return JSON.stringify({versionId:this.options.versionId,token:this.options.token,events:t.map((t=>t.c>1?{k:t.k,id:t.id,c:t.c}:{k:t.k,id:t.id}))})}sendWithBeacon(t){try{const e=this.reportBody(t),i="undefined"!=typeof navigator?navigator.sendBeacon:void 0;if("function"==typeof i&&i.call(navigator,this.reportAddress(),new Blob([e],{type:"text/plain"})))return void g.debug("[workflows] Counts handed to the browser to send",{eventCount:t.length})}catch(t){g.debug("[workflows] The browser would not take counts to send as the page closes",{error:t})}this.sendWithRequest(t)}sendWithRequest(e){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(this.reportAddress(),{method:"POST",mode:"cors",credentials:"omit",keepalive:!0,headers:{"Content-Type":"text/plain"},body:this.reportBody(e)});if(401===t.status)return g.warn("[workflows] The gateway refused the token for counts, so this embed stops reporting",{workflowId:this.options.workflowId}),void this.dispose();g.debug("[workflows] Counts sent",{eventCount:e.length,status:t.status})}catch(t){g.debug("[workflows] Counts could not be sent and were dropped",{eventCount:e.length,error:t})}}))}}const yt=/^[A-Za-z0-9_-]{1,64}$/,It=/^[A-Za-z0-9_.:-]{1,128}$/;function kt(t){return yt.test(t)}function Tt(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function At(e,i){return t(this,void 0,void 0,(function*(){const t=new AbortController,o=setTimeout((()=>t.abort()),1e4);try{const o=yield fetch(e,{method:"GET",mode:"cors",signal:t.signal});if(404===o.status)return{kind:"missing"};if(!o.ok)return{kind:"unreachable"};let s;try{s=yield o.json()}catch(t){return{kind:"unreadable"}}const n=function(t,e){var i;if(!Tt(t)||!0!==t.success||!Tt(t.data))return{kind:"unreadable"};const o=t.data;if("paused"===o.status)return{kind:"paused"};if("live"!==o.status)return{kind:"unreadable"};if("string"!=typeof o.versionId||!It.test(o.versionId))return{kind:"unreadable"};const s=ut(o.graph);if(!s.graph||s.issues.length>0)return g.warn("[workflows] The published graph could not be read, so the embed stays a plain embed",{workflowId:e,issueCount:s.issues.length,firstIssue:null===(i=s.issues[0])||void 0===i?void 0:i.code}),{kind:"unreadable"};const n={workflowId:"string"==typeof o.workflowId?o.workflowId:e,versionId:o.versionId,timezone:"string"==typeof o.timezone&&""!==o.timezone.trim()&&o.timezone.length<=64?o.timezone:"UTC",graph:s.graph};return"number"==typeof o.versionNumber&&Number.isInteger(o.versionNumber)&&(n.versionNumber=o.versionNumber),"string"==typeof o.publishedAt&&(n.publishedAt=o.publishedAt),"string"==typeof o.startCompositionId&&It.test(o.startCompositionId)&&(n.startCompositionId=o.startCompositionId),"string"==typeof o.eventToken&&""!==o.eventToken&&o.eventToken.length<=2048&&(n.eventToken=o.eventToken),{kind:"live",workflow:n}}(s,i);return"live"===n.kind?{kind:"live",workflow:n.workflow}:n}catch(t){return g.debug("[workflows] A host could not be reached",{workflowId:i,error:t}),{kind:"unreachable"}}finally{clearTimeout(o)}}))}const Et=new Map;function St(e,i={}){var o,s;if(!kt(e)||void 0!==i.versionId&&!It.test(i.versionId))return Promise.resolve({status:"unavailable",reason:"not_found"});const n=`${e}|${null!==(o=i.versionId)&&void 0!==o?o:""}|${(null!==(s=i.origins)&&void 0!==s?s:[]).join(",")}`,r=Et.get(n);if(r)return r;const d=function(e,i){return t(this,void 0,void 0,(function*(){var t;const o=null!==(t=i.origins)&&void 0!==t?t:y(),s=i.versionId?`/embed/workflows/${encodeURIComponent(e)}/versions/${encodeURIComponent(i.versionId)}`:`/embed/workflows/${encodeURIComponent(e)}`;let n=!1,r=!1;for(const t of o){const i=yield At(`${t}${s}`,e);if("live"===i.kind)return{status:"live",workflow:i.workflow,origin:t};if("paused"===i.kind)return{status:"paused"};"missing"===i.kind&&(n=!0),"unreadable"===i.kind&&(r=!0)}const d=n?"not_found":r?"unreadable":"unreachable";return g.debug("[workflows] The workflow is not available",{workflowId:e,reason:d}),{status:"unavailable",reason:d}}))}(e,i);return Et.set(n,d),d.finally((()=>{Et.get(n)===d&&Et.delete(n)})),d}const Ot={clicks:"click",submissions:"submit",plays:"play"},Ct=new Set(["__proto__","constructor","prototype"]);function Nt(t){const e=t.detail;return"object"!=typeof e||null===e||Array.isArray(e)?{}:e}function Ht(t,e){return("submissions"!==t.metric||"FORM"===e.tagName)&&(("plays"!==t.metric||"VIDEO"===e.tagName||"AUDIO"===e.tagName)&&(null!==t.selector?b(e,t.selector):"clicks"!==t.metric||null!==e.closest('button, a, input[type="button"], input[type="submit"], [role="button"], [onclick], [data-click-track]')))}function $t({stage:t,watch:i,emit:o}){var s;let n=!1;const r=[];if(i.inputTables.length>0){const e=new Map;for(const{table:t,column:o}of i.inputColumns){const i=null!==(s=e.get(t))&&void 0!==s?s:new Set;i.add(o),e.set(t,i)}const d=new Set,a=t=>{var s;if(n)return;const r=Nt(t),a=r.table;if("string"!=typeof a||!i.inputTables.includes(a))return;if("string"==typeof r.entryId&&""!==r.entryId){const t=`${a}:${r.entryId}`;if(d.has(t))return;if(d.add(t),d.size>100){const t=d.values().next().value;void 0!==t&&d.delete(t)}}const l=function(t,e){const i={};if("object"!=typeof t||null===t||Array.isArray(t))return i;for(const o of e){if(Ct.has(o))continue;if(!Object.prototype.hasOwnProperty.call(t,o))continue;const e=t[o];"string"==typeof e?i[o]=e.length>200?e.slice(0,200):e:("number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e)&&(i[o]=e)}return i}(r.values,null!==(s=e.get(a))&&void 0!==s?s:new Set);g.debug("[workflows] An entry was saved in a watched table",{table:a,valueCount:Object.keys(l).length}),o([{type:"input",table:a,values:l}])};t.addEventListener("widgetic:submitted",a),r.push((()=>t.removeEventListener("widgetic:submitted",a)))}if(i.actionIds.length>0){const s=t=>{if(n)return;const e=Nt(t);let s=null;"string"==typeof e.goalId?s=e.goalId:"string"==typeof e.metric&&""!==e.metric&&(s="string"==typeof e.goalTarget&&""!==e.goalTarget?`${e.metric}@${e.goalTarget}`:e.metric),null!==s&&i.actionIds.includes(s)&&(g.debug("[workflows] A widget reported a watched action",{actionId:s}),o([{type:"action",actionId:s}]))};t.addEventListener("widgetic:goal",s),r.push((()=>t.removeEventListener("widgetic:goal",s)));const a=[];for(const t of i.actionIds){const i=e(t);i&&(d=i.metric,Object.prototype.hasOwnProperty.call(Ot,d))&&a.push({actionId:t,metric:i.metric,selector:i.selector})}if(a.length>0){let e=null,i=()=>{};const s=t=>{const e=t.target instanceof Element?t.target:null;if(!e)return[];const i=[];for(const o of a)Ot[o.metric]===t.type&&Ht(o,e)&&i.push({type:"action",actionId:o.actionId});return i},d=t=>{if(n)return;const e=s(t);0!==e.length&&(g.debug("[workflows] A watched action happened in the widget",{actionIds:e.map((t=>t.actionId))}),o(e))},l=()=>{var o;const s=t.querySelector("[data-widgetic-direct]"),n=null!==(o=null==s?void 0:s.shadowRoot)&&void 0!==o?o:null;if(!n||n===e)return;i();const r=new Set(a.map((t=>Ot[t.metric])));for(const t of r)n.addEventListener(t,d,!0);e=n,i=()=>{for(const t of r)n.removeEventListener(t,d,!0);e=null,i=()=>{}}};t.addEventListener("widgetic:ready",l),r.push((()=>t.removeEventListener("widgetic:ready",l))),r.push((()=>i())),l()}}var d;return{stop:()=>{if(!n){n=!0;for(const t of r)try{t()}catch(t){g.debug("[workflows] A listener could not be removed",{error:t})}}}}}const Wt=50,Mt=2e3,Rt=150,Lt=5,Pt=300,xt=2e4;function jt(t,e,i,o){const s=t.getAttribute(e);if(null===s||!/^\d+$/.test(s.trim()))return i;const n=Number.parseInt(s.trim(),10);return Number.isFinite(n)?Math.min(n,o):i}function Ft(t,e,i){const o="number"==typeof i&&Number.isFinite(i)&&i>0?Math.min(e.maxHeight,Math.floor(i)):e.maxHeight,s=Math.min(e.minHeight,o);return Number.isNaN(t)?s:Math.max(s,Math.min(o,Math.ceil(t)))}function Bt(t,e,i){return null===t||e!==t&&Math.abs(e-t)>=i}const _t=["width","height","resize","resize-mode","render-mode","use-iframe","theme","mode","colors","sandbox","autoload","adaptive","responsive"],zt=["values","context","media-resolver"],Dt=["design","content","content-items","contentitems","items"];function Ut(t){if("undefined"==typeof ResizeObserver)return null;try{return new ResizeObserver((e=>{t(e.map((t=>({target:t.target,height:t.contentRect.height}))))}))}catch(t){return g.debug("[workflows] The browser could not watch heights",{error:t}),null}}function Vt(t){return t.getBoundingClientRect().height}function qt(){try{return"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch(t){return!1}}function Zt(t){return"number"==typeof t&&Number.isFinite(t)&&t>0}class Gt{constructor(t){var e;this.current=null,this.incoming=null,this.heightObserver=null,this.attributeObserver=null,this.autoscaleOn=!1,this.appliedHeight=null,this.debounceTimer=null,this.pendingHeight=null,this.destroyed=!1,this.warnedAboutFrameWithoutHeight=!1,this.host=t.host,this.services=t.services,this.prefersReducedMotion=null!==(e=t.prefersReducedMotion)&&void 0!==e?e:qt,this.widthOverride=t.widthOverride&&""!==t.widthOverride?t.widthOverride:null,this.viewportElement=document.createElement("div"),this.viewportElement.setAttribute("data-widgetic-workflow-viewport","1"),this.viewportElement.setAttribute("data-widgetic-internal","1"),this.viewportElement.style.display="block",this.observeMirroredAttributes()}currentStage(){var t,e;return null!==(e=null===(t=this.current)||void 0===t?void 0:t.element)&&void 0!==e?e:null}showFirstStage(t){if(this.current)return{stage:this.current.element,ready:Promise.resolve({status:"ready"})};this.viewportElement.isConnected||this.host.appendChild(this.viewportElement),this.holdRoomFor(t);const e=this.buildStage(t,!0);this.current=e;const i=this.waitUntilShown(e,null,(t=>{if("ready"===t.status&&!this.destroyed&&this.autoscaleOn&&this.current===e){const t=this.measure(e.element);Zt(t)&&this.applyHeight(t,"immediate")}}));return this.viewportElement.appendChild(e.element),this.services.hydrate(e.element),{stage:e.element,ready:i}}enableAutoscale(){var t,e;if(!this.destroyed&&!this.autoscaleOn&&(this.autoscaleOn=!0,this.viewportElement.style.position="relative",this.viewportElement.style.overflow="hidden",this.current&&this.positionAsLayer(this.current.element),this.heightObserver=(null!==(t=this.services.createHeightObserver)&&void 0!==t?t:Ut)((t=>this.onHeightsReported(t))),this.current)){null===(e=this.heightObserver)||void 0===e||e.observe(this.current.element);const t=this.measure(this.current.element);Zt(t)&&this.applyHeight(t,"immediate")}}releaseAutoscale(){var t;if(this.destroyed)return;this.autoscaleOn=!1,this.clearHeightTimer(),null===(t=this.heightObserver)||void 0===t||t.disconnect(),this.heightObserver=null,this.appliedHeight=null;const e=this.viewportElement.style;for(const t of["position","overflow","height","min-height","transition"])e.removeProperty(t);this.current&&this.positionInFlow(this.current.element)}swapTo(e){return t(this,void 0,void 0,(function*(){var t,o,s;if(this.destroyed)return{status:"failed",reason:"stopped"};if(this.incoming)return{status:"failed",reason:"busy"};this.enableAutoscale();const n=this.buildStage(e,!1);this.incoming=n,this.hideBeside(n.element);const r=this.waitUntilShown(n,null!==(t=this.services.readyTimeoutMilliseconds)&&void 0!==t?t:8e3);this.viewportElement.appendChild(n.element),this.services.hydrate(n.element);const d=yield r;if(this.destroyed)return{status:"failed",reason:"stopped"};if(this.incoming=null,"failed"===d.status)return this.removeStage(n),"timeout"===d.reason&&i(this.host,e,"workflow_step_timeout"),g.debug("[workflows] The next composition could not be shown, so the visitor stays where they are",{compositionId:e,reason:d.reason}),Object.assign({status:"failed",reason:"stopped"===d.reason?"stopped":d.reason},d.code?{code:d.code}:{});const a=this.current;this.revealInPlace(n.element),this.current=n,null===(o=this.heightObserver)||void 0===o||o.observe(n.element);const l=this.measure(n.element);return Zt(l)&&this.applyHeight(l,"immediate"),a&&(null===(s=this.heightObserver)||void 0===s||s.unobserve(a.element),this.removeStage(a)),{status:"shown",stage:n.element}}))}destroy(){var t,e,i;if(this.destroyed)return;this.destroyed=!0,this.clearHeightTimer(),null===(t=this.heightObserver)||void 0===t||t.disconnect(),this.heightObserver=null,null===(e=this.attributeObserver)||void 0===e||e.disconnect(),this.attributeObserver=null;const o=[this.current,this.incoming];this.current=null,this.incoming=null;for(const t of o)t&&(null===(i=t.cancelWait)||void 0===i||i.call(t),this.removeStage(t));this.viewportElement.remove()}buildStage(t,e){var i,o,s;const n=document.createElement("widgetic");n.setAttribute("composition-id",t),n.setAttribute("data-widgetic-workflow-stage","1"),n.style.display="block";for(const t of _t){const e=this.host.getAttribute(t);null!==e&&n.setAttribute(t,e)}this.widthOverride&&n.setAttribute("width",this.widthOverride);for(const t of zt){const e=this.host.getAttribute(t);null!==e&&n.setAttribute(t,e)}const r=t===(null!==(i=this.host.getAttribute("composition-id"))&&void 0!==i?i:"").trim();r&&this.copyWhatThePageWroteForTheTagComposition(n);const d={element:n,compositionId:t,reportedHeight:!1,cancelWait:null,stopListening:()=>{}},a=t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.height;if("number"!=typeof i||!Zt(i))return;const o=n.querySelector("iframe");o&&(o.style.height=`${Math.ceil(i)}px`,d.reportedHeight=!0)};n.addEventListener("widgetic:resize",a),d.stopListening=()=>n.removeEventListener("widgetic:resize",a);try{null===(s=(o=this.services).onStageCreated)||void 0===s||s.call(o,n,{compositionId:t,isFirst:e,carriesPageContent:r})}catch(e){g.debug("[workflows] A listener for a new stage failed",{compositionId:t,error:e})}return d}copyWhatThePageWroteForTheTagComposition(t){for(const e of Array.from(this.host.attributes))A(e.name)||t.setAttribute(e.name,e.value);for(const e of Dt){const i=this.host.getAttribute(e);null!==i&&t.setAttribute(e,i)}for(const e of E(this.host))t.appendChild(e.cloneNode(!0))}observeMirroredAttributes(){const t="undefined"!=typeof MutationObserver?MutationObserver:null;if(t)try{this.attributeObserver=new t((t=>{t.some((t=>{var e;return"attributes"===t.type&&zt.includes(null!==(e=t.attributeName)&&void 0!==e?e:"")}))&&this.mirrorAttributesToStages()})),this.attributeObserver.observe(this.host,{attributes:!0,attributeFilter:[...zt]})}catch(t){this.attributeObserver=null,g.debug("[workflows] The tag cannot be watched for changes",{error:t})}}mirrorAttributesToStages(){for(const t of[this.current,this.incoming])if(t)for(const e of zt){const i=this.host.getAttribute(e);null===i?t.element.removeAttribute(e):t.element.getAttribute(e)!==i&&t.element.setAttribute(e,i)}}waitUntilShown(t,e,i){return new Promise((o=>{const s=t.element;let n=null,r=!1;const d=e=>{if(!r){r=!0,null!==n&&clearTimeout(n),s.removeEventListener("widgetic:ready",a),s.removeEventListener("widgetic:error",l),s.removeEventListener("load",u,!0),t.cancelWait=null;try{null==i||i(e)}catch(e){g.debug("[workflows] A stage could not be settled",{compositionId:t.compositionId,error:e})}o(e)}},a=()=>d({status:"ready"}),l=t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.code;d(Object.assign({status:"failed",reason:"error"},"string"==typeof i?{code:i}:{}))},u=t=>{t.target instanceof HTMLIFrameElement&&d({status:"ready"})};s.addEventListener("widgetic:ready",a),s.addEventListener("widgetic:error",l),s.addEventListener("load",u,!0),t.cancelWait=()=>d({status:"failed",reason:"stopped"}),null!==e&&(n=setTimeout((()=>d({status:"failed",reason:"timeout"})),e))}))}removeStage(t){var e,i;t.stopListening(),t.element.querySelector("iframe")&&!t.reportedHeight&&this.noteFrameWithoutHeight(t.compositionId),t.element.remove();try{null===(i=(e=this.services).onStageRemoved)||void 0===i||i.call(e,t.element)}catch(e){g.debug("[workflows] A listener for a removed stage failed",{compositionId:t.compositionId,error:e})}}noteFrameWithoutHeight(t){this.warnedAboutFrameWithoutHeight||(this.warnedAboutFrameWithoutHeight=!0,g.debug("[workflows] A widget in a frame does not report its height (widgetic:resize), so the embed keeps the height of its frame",{compositionId:t}))}hideBeside(t){this.positionAsLayer(t),t.style.visibility="hidden",t.style.pointerEvents="none",t.setAttribute("aria-hidden","true")}revealInPlace(t){t.style.removeProperty("visibility"),t.style.removeProperty("pointer-events"),t.removeAttribute("aria-hidden")}positionAsLayer(t){t.style.position="absolute",t.style.top="0",t.style.left="0",t.style.width="100%"}positionInFlow(t){for(const e of["position","top","left","width"])t.style.removeProperty(e)}measure(t){var e;try{return(null!==(e=this.services.measureStageHeight)&&void 0!==e?e:Vt)(t)}catch(t){return g.debug("[workflows] The height of a stage could not be read",{error:t}),0}}holdRoomFor(t){const e=I(t);if(null===e)return;const i=this.settings();this.viewportElement.style.minHeight=`${Ft(e,i,this.overlayCap())}px`}settings(){return function(t,e={}){const i=jt(t,"autoscale-min-height",Wt,xt),o=jt(t,"autoscale-max-height",Mt,xt);return{minHeight:i,maxHeight:Math.max(o,i),debounceDelay:jt(t,"autoscale-debounce",Rt,5e3),threshold:jt(t,"autoscale-threshold",Lt,xt),animate:"false"!==t.getAttribute("autoscale-animate")&&!0!==e.prefersReducedMotion,animationDuration:jt(t,"autoscale-animation-duration",Pt,5e3)}}(this.host,{prefersReducedMotion:this.prefersReducedMotion()})}overlayCap(){return this.host.hasAttribute(o)?Math.floor(.9*window.innerHeight):null}onHeightsReported(t){if(!this.destroyed&&this.autoscaleOn&&this.current)for(const e of t)e.target===this.current.element&&Zt(e.height)&&this.applyHeight(e.height,"observed")}applyHeight(t,e){const i=this.settings(),o=Ft(t,i,this.overlayCap());if("immediate"===e)return this.clearHeightTimer(),void this.setHeight(o,i);Bt(this.appliedHeight,o,i.threshold)?(this.pendingHeight=o,null!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=null;const t=this.pendingHeight;if(this.pendingHeight=null,null===t||this.destroyed||!this.autoscaleOn)return;const e=this.settings();Bt(this.appliedHeight,t,e.threshold)&&this.setHeight(t,e)}),i.debounceDelay)):o===this.appliedHeight&&this.clearHeightTimer()}setHeight(t,e){var i;const o=this.viewportElement.style,s=null!==this.appliedHeight&&this.appliedHeight!==t;if(o.setProperty("transition",e.animate&&s?`height ${e.animationDuration}ms ease`:"none"),o.height=`${t}px`,o.removeProperty("min-height"),this.appliedHeight=t,this.current){const e=Number.parseInt(null!==(i=this.host.getAttribute("height"))&&void 0!==i?i:"",10);k(this.current.compositionId,t,Number.isFinite(e)?e:t)}}clearHeightTimer(){null!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingHeight=null}}const Jt=3e4;function Kt(t,e,i){var o;try{h(t,f(e,i)),null===(o=p(t))||void 0===o||o.sendWorkflowWatch(i)}catch(t){g.debug("[workflows] A widget could not be told what to report",{compositionId:e,error:t})}}function Qt(t){try{T(t).then((t=>{var e;const i="found"===t.status?null===(e=t.payload.direct)||void 0===e?void 0:e.moduleUrl:void 0;i&&c(i)})).catch((()=>{}))}catch(e){g.debug("[workflows] A composition could not be got ready",{compositionId:t,error:e})}}function Xt(t){const e=window;if("function"==typeof e.requestIdleCallback){const i=e.requestIdleCallback((()=>t()),{timeout:5e3});return()=>{var t;return null===(t=e.cancelIdleCallback)||void 0===t?void 0:t.call(e,i)}}const i=setTimeout(t,1500);return()=>clearTimeout(i)}class Yt{constructor(t,e,i,o,s){this.host=t,this.workflowId=e,this.tagCompositionId=i,this.options=o,this.services=s,this.mode="loading",this.stages=new Map,this.pageEvents=new n,this.removeListeners=[],this.workflow=null,this.index=null,this.counts=null,this.position=null,this.stepping=!1,this.pendingStageNodeId=null,this.retryTimer=null,this.scheduleTimers=new Set,this.cancelIdleWork=null,this.readiedCompositions=new Set,this.displayBeforeMounting="",this.onPageEvent=t=>{if("ended"===this.mode||"plain"===this.mode)return;const e=r(t.detail);e?"running"!==this.mode||this.stepping?this.pageEvents.add(e):this.hasEnded()||this.react([{type:"pageEvent",name:e.name,values:e.values}]):g.debug("[workflows] An event of the page was ignored: it is not one a workflow can wait for")},this.onVisibilityChange=()=>{"running"!==this.mode||this.stepping||this.hasEnded()||this.armSchedules()};const d=s.viewport;this.viewport=new Gt(Object.assign(Object.assign(Object.assign({host:t},d.prefersReducedMotion?{prefersReducedMotion:d.prefersReducedMotion}:{}),o.width?{widthOverride:o.width}:{}),{services:Object.assign(Object.assign(Object.assign(Object.assign({hydrate:o.hydrate},d.createHeightObserver?{createHeightObserver:d.createHeightObserver}:{}),d.measureStageHeight?{measureStageHeight:d.measureStageHeight}:{}),void 0!==d.readyTimeoutMilliseconds?{readyTimeoutMilliseconds:d.readyTimeoutMilliseconds}:{}),{onStageCreated:t=>this.onStageCreated(t),onStageRemoved:t=>this.onStageRemoved(t)})}))}start(){var t;const e=function(t,e=Date.now()){const i=ht(t),o=m(i);if(null===o)return null;try{const i=JSON.parse(o);if("object"!=typeof i||null===i||Array.isArray(i))return null;const s=i;return 1!==s.v?null:ft(s.versionId)&&ft(s.nodeId)&&ft(s.compositionId)&&pt(s.startedAt)&&pt(s.reachedAt)?s.startedAt>e+864e5?null:e-s.startedAt>2592e6?(gt(t),g.debug("[workflows] The visitor's position is older than 30 days and was forgotten",{workflowId:t}),null):{versionId:s.versionId,nodeId:s.nodeId,compositionId:s.compositionId,startedAt:s.startedAt,reachedAt:Math.min(s.reachedAt,e)}:null}catch(e){return g.debug("[workflows] The kept position could not be read and is ignored",{workflowId:t,error:e}),null}}(this.workflowId),i=null!==(t=null==e?void 0:e.compositionId)&&void 0!==t?t:this.tagCompositionId;this.listenToThePage();const{ready:o}=this.viewport.showFirstStage(i);this.displayBeforeMounting=this.host.style.display,this.options.markMounted(this.host),this.run(e,i,o)}run(e,i,o){return t(this,void 0,void 0,(function*(){var t;try{const[s,n]=yield Promise.all([this.services.fetchWorkflow(this.workflowId),o]);if(this.hasEnded())return;let r=e,d=i;if("failed"===n.status){if("stopped"===n.reason)return;if(!e||e.compositionId===this.tagCompositionId)return void this.refuse(n.code);{g.debug("[workflows] The composition a returning visitor was on cannot be shown, so they start again",{compositionId:e.compositionId}),gt(this.workflowId),r=null;const i=yield this.viewport.swapTo(this.tagCompositionId);if(this.hasEnded())return;if("shown"!==i.status)return void this.refuse(null!==(t=n.code)&&void 0!==t?t:"failed"===i.status?i.code:void 0);d=this.tagCompositionId}}if("live"!==s.status)return g.debug("[workflows] The workflow is not running, so the tag is a plain embed",{workflowId:this.workflowId,status:s.status}),void(yield this.becomePlain(d));let a=s.workflow,l=s.origin;if(r&&r.versionId!==a.versionId){const t=yield this.services.fetchWorkflow(this.workflowId,{versionId:r.versionId});if(this.hasEnded())return;"live"===t.status&&t.workflow.versionId===r.versionId?(a=t.workflow,l=t.origin):(g.debug("[workflows] The version a visitor started on cannot be read, so they continue as a new visitor",{versionId:r.versionId}),gt(this.workflowId),r=null)}const u=O(a.graph);let c=r&&this.fitsTheGraph(r,a,u)?r:null;const h=null===c;if(null===c){r&&(g.debug("[workflows] The place a visitor was kept at is not in the workflow, so they continue as a new visitor"),gt(this.workflowId));const t=function(t,e){for(const i of t.nodes)if("composition"===i.type&&i.compositionId===e)return i}(a.graph,this.tagCompositionId);if(!t)return g.debug("[workflows] The composition of the tag is not a block of the workflow, so the tag is a plain embed",{compositionId:this.tagCompositionId}),void(yield this.becomePlain(d));if(d!==this.tagCompositionId){const t=yield this.viewport.swapTo(this.tagCompositionId);if(this.hasEnded())return;if("shown"!==t.status)return void(yield this.becomePlain(d))}const e=Date.now();c={versionId:a.versionId,nodeId:t.id,compositionId:this.tagCompositionId,startedAt:e,reachedAt:e}}this.activate(a,l,u,c,h)}catch(t){g.warn("[workflows] The workflow stopped working, so the tag stays as it is",{workflowId:this.workflowId,error:t}),this.becomePlainWithoutWaiting()}}))}fitsTheGraph(t,e,i){if(t.versionId!==e.versionId)return!1;const o=i.nodesById.get(t.nodeId);return H(o)&&o.compositionId===t.compositionId}activate(t,e,i,o,s){var n;this.workflow=t,this.index=i,this.position=o,this.mode="running";const r=this.services.createCounts({workflowId:this.workflowId,versionId:t.versionId,token:null!==(n=t.eventToken)&&void 0!==n?n:null,apiOrigin:e,isActive:()=>"ended"!==this.mode&&this.host.isConnected});r.start(),this.counts=r,s&&(mt(this.workflowId,o),r.count("n",o.nodeId)),g.debug("[workflows] The workflow runs",{workflowId:this.workflowId,versionId:t.versionId,isNewVisitor:s}),this.viewport.enableAutoscale();const d=this.viewport.currentStage();d&&this.armStage(d,o.nodeId),this.armSchedules(),this.getNextCompositionsReady(),this.drainPageEvents()}becomePlain(e){return t(this,void 0,void 0,(function*(){if(this.mode="plain",this.pageEvents.clear(),e!==this.tagCompositionId){const t=yield this.viewport.swapTo(this.tagCompositionId);if(this.hasEnded())return;"shown"!==t.status&&g.debug("[workflows] The composition of the tag could not be shown")}this.viewport.releaseAutoscale()}))}becomePlainWithoutWaiting(){"ended"!==this.mode&&(this.mode="plain",this.pageEvents.clear(),this.cancelRetry(),this.cancelSchedules(),this.viewport.releaseAutoscale())}refuse(t){const e=this.viewport.currentStage(),i=(null==e?void 0:e.getAttribute(d))||t||"NOT_FOUND";this.stop(),this.host.removeAttribute("data-widgetic-mounting"),this.host.removeAttribute("data-widgetic-mounted"),this.host.style.display=this.displayBeforeMounting,this.host.setAttribute(d,i),g.debug("[workflows] The composition of the tag cannot be shown",{workflowId:this.workflowId,reason:i})}listenToThePage(){this.host.addEventListener(a,this.onPageEvent),document.addEventListener("visibilitychange",this.onVisibilityChange),this.removeListeners.push((()=>this.host.removeEventListener(a,this.onPageEvent)),(()=>document.removeEventListener("visibilitychange",this.onVisibilityChange)))}drainPageEvents(){const t=this.pageEvents.take();for(let e=0;e<t.length;e+=1){if("running"!==this.mode)return;if(this.stepping){for(const i of t.slice(e))this.pageEvents.add(i);return}const i=t[e];this.react([{type:"pageEvent",name:i.name,values:i.values}])}}onStageCreated(t){if(this.stages.set(t,{signals:null,stopWatchingReady:null}),null!==this.pendingStageNodeId){const e=this.pendingStageNodeId;this.pendingStageNodeId=null,this.armStage(t,e)}}onStageRemoved(t){var e,i;const o=this.stages.get(t);null===(e=null==o?void 0:o.signals)||void 0===e||e.stop(),null===(i=null==o?void 0:o.stopWatchingReady)||void 0===i||i.call(o),this.stages.delete(t)}armStage(t,e){var i,o,s;const n=this.workflow,r=this.index;if(!n||!r)return;const d=r.nodesById.get(e);if(!H(d))return;const a=null!==(i=this.stages.get(t))&&void 0!==i?i:{signals:null,stopWatchingReady:null};null===(o=a.signals)||void 0===o||o.stop(),null===(s=a.stopWatchingReady)||void 0===s||s.call(a),this.stages.set(t,a);const u=et(n.graph,e,{index:r});a.signals=$t({stage:t,watch:u,emit:e=>this.onSignals(t,e)});const c=l(u);if(0===c.tables.length&&0===c.fields.length&&0===c.goals.length)return;const h=()=>this.services.deliverWatch(t,d.compositionId,c);h(),t.addEventListener("widgetic:ready",h),a.stopWatchingReady=()=>t.removeEventListener("widgetic:ready",h)}onSignals(t,e){"running"!==this.mode||this.stepping||this.hasEnded()||t===this.viewport.currentStage()&&this.react(e)}react(t){const e=this.workflow,i=this.index,o=this.position;if(e&&i&&o)for(const s of t){let t;try{t=X(e.graph,{nodeId:o.nodeId},s,{index:i})}catch(t){g.debug("[workflows] The engine could not decide on a signal",{signal:s.type,error:t});continue}if("moved"===t.outcome)return void this.moveOn(t,!1)}}moveOn(e,i){return t(this,void 0,void 0,(function*(){const t=this.index,o=this.position;if(!t||!o)return;const s=t.nodesById.get(e.position.nodeId);if(!H(s))return;let n;this.stepping=!0,this.cancelRetry(),this.cancelSchedules(),this.pendingStageNodeId=s.id;try{n=yield this.viewport.swapTo(s.compositionId)}catch(t){g.debug("[workflows] The next composition could not be built",{compositionId:s.compositionId,error:t}),n={status:"failed",reason:"error"}}this.pendingStageNodeId=null,this.stepping=!1,this.hasEnded()||("shown"===n.status?this.completeStep(e,s,o):this.failStep(e,s,o,i))}))}completeStep(t,e,i){const o=Object.assign(Object.assign({},i),{nodeId:e.id,compositionId:e.compositionId,reachedAt:Date.now()});this.position=o,mt(this.workflowId,o),this.countStep(i.nodeId,t,e.id),g.debug("[workflows] The visitor moved on",{from:i.compositionId,to:e.compositionId}),this.host.dispatchEvent(new CustomEvent(u,{detail:{workflowId:this.workflowId,from:i.compositionId,to:e.compositionId},bubbles:!0,composed:!0})),this.armSchedules(),this.getNextCompositionsReady(),this.drainPageEvents()}countStep(t,e,i){const o=this.counts,s=this.index;if(!o||!s)return;const n=N(s,t).find((t=>t.target===e.firedTriggerId));n&&o.count("e",n.id);for(const t of e.passedNodeIds)o.count("n",t);for(const t of e.takenEdgeIds)o.count("e",t);o.count("n",i)}failStep(t,e,i,o){var s;null===(s=this.counts)||void 0===s||s.count("f",e.id),g.debug("[workflows] The next composition could not be shown, so the visitor stays where they are",{compositionId:e.compositionId,isRetry:o}),this.armSchedules(),o||this.scheduleRetry(t,i.nodeId),this.drainPageEvents()}scheduleRetry(t,e){this.cancelRetry(),this.retryTimer=setTimeout((()=>{var i;this.retryTimer=null,"running"!==this.mode||this.stepping||this.hasEnded()||(null===(i=this.position)||void 0===i?void 0:i.nodeId)===e&&this.moveOn(t,!0)}),3e4)}cancelRetry(){null!==this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=null}armSchedules(){this.cancelSchedules();const t=this.workflow,e=this.index,i=this.position;if("running"===this.mode&&!this.stepping&&t&&e&&i)for(const{triggerId:o,schedule:s}of et(t.graph,i.nodeId,{index:e}).schedules){const t=J(s,i.reachedAt,Date.now());void 0!==t?this.waitFor(o,s,i.nodeId,t):g.debug("[workflows] A Scheduled trigger has no usable time and is ignored",{triggerId:o})}}waitFor(t,e,i,o){const s=setTimeout((()=>{this.scheduleTimers.delete(s);const o=this.position;if("running"!==this.mode||this.stepping||this.hasEnded()||!o||o.nodeId!==i)return;const n=J(e,o.reachedAt,Date.now());void 0!==n&&(n>0?this.waitFor(t,e,i,n):(g.debug("[workflows] A wait is over",{triggerId:t}),this.react([{type:"scheduled",triggerId:t}])))}),Math.min(o,432e5));this.scheduleTimers.add(s)}cancelSchedules(){for(const t of this.scheduleTimers)clearTimeout(t);this.scheduleTimers.clear()}getNextCompositionsReady(){var t,e;null===(t=this.cancelIdleWork)||void 0===t||t.call(this),this.cancelIdleWork=null;const i=null===(e=this.position)||void 0===e?void 0:e.nodeId;i&&(this.cancelIdleWork=this.services.whenIdle((()=>{var t;if(this.cancelIdleWork=null,"running"!==this.mode||this.hasEnded()||(null===(t=this.position)||void 0===t?void 0:t.nodeId)!==i)return;let e=0;for(const t of this.compositionsReachableFrom(i))if(!this.readiedCompositions.has(t)){if(e>=5)break;this.readiedCompositions.add(t),e+=1,this.services.prefetchComposition(t)}})))}compositionsReachableFrom(t){const e=this.index;if(!e)return[];const i=[],o=new Set;for(const s of W(e,t)){const t=[s.id];for(;t.length>0;){const s=t.pop();if(!o.has(s)){o.add(s);for(const o of N(e,s)){const s=e.nodesById.get(o.target);H(s)?i.includes(s.compositionId)||i.push(s.compositionId):$(s)&&t.push(s.id)}}}}return i}hasEnded(){return"ended"===this.mode||!this.host.isConnected&&(g.debug("[workflows] The tag left the page, so its workflow ends",{workflowId:this.workflowId}),this.stop(),!0)}stop(){var t,e,i,o,s;if("ended"!==this.mode){try{null===(t=this.counts)||void 0===t||t.flushBeforeLeaving()}catch(t){g.debug("[workflows] The last counts could not be sent",{error:t})}this.mode="ended",this.cancelRetry(),this.cancelSchedules(),null===(e=this.cancelIdleWork)||void 0===e||e.call(this),this.cancelIdleWork=null;for(const t of this.removeListeners.splice(0))t();for(const t of this.stages.values())null===(i=t.signals)||void 0===i||i.stop(),null===(o=t.stopWatchingReady)||void 0===o||o.call(t);this.stages.clear(),this.pageEvents.clear();try{null===(s=this.counts)||void 0===s||s.dispose()}catch(t){g.debug("[workflows] The counts could not be closed",{error:t})}this.viewport.destroy()}}}function te(t,e){var i,o,n;const r=(null!==(i=t.getAttribute("workflow-id"))&&void 0!==i?i:"").trim(),d=(null!==(o=t.getAttribute("composition-id"))&&void 0!==o?o:"").trim();if(!kt(r)||""===d)return g.debug("[workflows] The tag is not a workflow embed, so it is embedded as it is",{workflowId:r,tagCompositionId:d}),null;const a={fetchWorkflow:St,createCounts:t=>new bt(t),deliverWatch:Kt,prefetchComposition:Qt,whenIdle:Xt,viewport:{}},l=Object.assign(Object.assign(Object.assign({},a),e.services),{viewport:Object.assign(Object.assign({},a.viewport),null===(n=e.services)||void 0===n?void 0:n.viewport)}),u=new Yt(t,r,d,e,l);try{u.start()}catch(t){return g.warn("[workflows] The workflow could not start, so the tag is embedded as it is",{workflowId:r,error:t}),u.stop(),null}const c={stop:()=>u.stop()};return s(t,c),c}export{Jt as RETRY_AFTER_FAILED_STEP_MILLISECONDS,te as startWorkflowEmbed};
|
|
@@ -1 +1 @@
|
|
|
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.
|
|
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.G})))),this.loadChunk("scanner",(()=>import("./chunks/scanner.js").then((function(t){return t.r})))),this.loadChunk("scanner",(()=>import("./chunks/scanner.js").then((function(t){return t.s}))))];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.l})))),this.loadChunk("renderers",(()=>import("./chunks/renderers.js").then((function(t){return t.j})))),this.loadChunk("renderers",(()=>import("./chunks/renderers.js").then((function(t){return t.k}))))];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.A}))))];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")));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.D})),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{b as n,W as o,c as u,G as v,d as w,e as b,f as y,E as T}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 x,g as D,C as _,V as R,q as O,e as W,a as N,T as z,d as P}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 Q,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 K,e as U}from"./chunks/ABTestManager.js";import{_ as V}from"./chunks/vendor.js";import{k as $}from"./chunks/scanner.js";export{e as detectBrowserCapabilities,j as determineBestRenderMode,f 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/display.js";import"./chunks/performance.js";import"./chunks/security.js";class G{constructor(e){this.deviceDetector=n(),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(),x.debug("[AnalyticsTracker] Initialized",{compositionId:this.config.compositionId,sessionId:this.sessionId})}static getInstance(e){if(!G.instance&&e&&(G.instance=new G(e)),!G.instance)throw new Error("AnalyticsTracker must be initialized with config first");return G.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){x.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){x.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?(x.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(),x.debug("[AnalyticsTracker] Event queued",{eventType:e.eventType,queueSize:this.eventQueue.length})):x.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 V(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(),x.debug("[AnalyticsTracker] Batch sent successfully",{batchSize:e.length,remainingQueue:this.eventQueue.length})}catch(t){x.error("[AnalyticsTracker] Failed to send batch",{error:t,batchSize:e.length}),this.eventQueue.unshift(...e),setTimeout((()=>this.processBatch()),5e3)}}))}sendEventBatch(e){return V(this,void 0,void 0,(function*(){if(!this.config.apiEndpoint)return void x.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 D(),n=new _({basePath:this.config.apiEndpoint,accessToken:()=>V(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${R}`}}),s=new O(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){x.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||[],x.debug("[AnalyticsTracker] Loaded queued events from storage",{count:this.eventQueue.length})):localStorage.removeItem(this.STORAGE_KEY)}}catch(e){x.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),x.debug("[AnalyticsTracker] Configuration updated",e)}clearQueue(){this.eventQueue=[],this.config.enableLocalStorage&&localStorage.removeItem(this.STORAGE_KEY),x.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)),G.instance=null,x.debug("[AnalyticsTracker] Destroyed")}}const Y="undefined"!=typeof HTMLElement?HTMLElement:class{};class J extends Y{constructor(){super(),this.experimentId=null,this.assignment=null,this.widgetInstance=null,this.impressionTracked=!1,this.conversionListeners=new Map,this.manager=K.getInstance(),this.widgetManager=o.getInstance(),this.analyticsTracker=G.getInstance(),this.attachShadow({mode:"open"}),this.setupEventListeners()}static get observedAttributes(){return["experiment-id","user-id","session-id"]}connectedCallback(){return V(this,void 0,void 0,(function*(){try{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return W.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 W.warn("No variant assignment received",{experimentId:this.experimentId}),void this.renderError("Test not available");this.setupGoalListeners(),yield this.renderVariant(),yield this.trackImpression(),this.setupConversionTracking(),W.info("A/B test element initialized",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){W.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 V(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){W.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 W.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 W.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(),W.debug("Conversion tracking setup complete",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){W.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?U(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&&!U(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&&!U(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=u(e))||void 0===t||t.sendAbGoal({metric:i,goalTarget:this.assignment.goalTarget||null})}catch(e){W.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(v);this.manager.setWidgetReportsGoals(this.experimentId,n),this.assignment.goalTarget&&!n&&W.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 V(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}),W.debug("Impression tracked",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){W.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;W.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;W.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){W.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=w(),x.debug("[TranslationElement] Created translation element")}connectedCallback(){if(this.isInitialized)x.debug("[TranslationElement] Already initialized, skipping");else{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return x.error("[TranslationElement] Missing experiment-id attribute"),void this.displayError("Missing experiment-id attribute");x.debug(`[TranslationElement] Connected with experiment ID: ${this.experimentId}`),this.initializeTranslation()}}disconnectedCallback(){x.debug("[TranslationElement] Disconnected"),this.cleanup()}initializeTranslation(){return V(this,void 0,void 0,(function*(){try{this.isInitialized=!0;const e=this.detectBrowserLanguages();if(x.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),x.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),x.info("[TranslationElement] Translation experiment loaded successfully",{experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,compositionId:t})}catch(e){x.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 V(this,void 0,void 0,(function*(){try{const t=N(),i=new _({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new z(i),s=yield n.getTranslationConfig({id:e});return(null==s?void 0:s.data)||null}catch(e){throw x.error("[TranslationElement] Error fetching translation experiment:",e),e}}))}findBestLanguageMatch(e,t){const i=Object.keys(t.languageCompositions||{}),n=t.rootLanguage||"en";x.debug("[TranslationElement] Available languages:",i),x.debug("[TranslationElement] Root language:",n);for(const t of e)if(i.includes(t))return x.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 x.debug("[TranslationElement] Found base language match:",n),this.trackFallbackUsage(t,n,"language_family").catch((e=>{x.debug("[TranslationElement] Failed to track language family fallback:",e)})),n}x.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=>{x.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 V(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=>{x.warn("[TranslationElement] Failed to send analytics:",e)}))}catch(e){x.warn("[TranslationElement] Error in analytics tracking:",e)}}sendAnalytics(e){return V(this,void 0,void 0,(function*(){try{const t=N(),i=new _({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new z(i);yield n.submitTranslationAnalyticsEvent({id:this.experimentId,submitTranslationAnalyticsEventRequest:e})}catch(e){x.debug("[TranslationElement] Analytics request failed:",e)}}))}trackFallbackUsage(e,t,i){return V(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),x.debug("[TranslationElement] Fallback usage tracked:",{requested:e,selected:t,fallbackType:i})}catch(e){x.debug("[TranslationElement] Failed to track fallback usage:",e)}}))}handleInitializationError(e){return V(this,void 0,void 0,(function*(){if(this.retryCount<this.maxRetries){this.retryCount++,x.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){x.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),x.info("[TranslationElement] Custom element registered")))}catch(e){x.error("[TranslationElement] Failed to register custom element:",e)}}}Z.register();const ee=b();"undefined"!=typeof window&&"undefined"!=typeof customElements&&(Q(),J.register(),Z.register()),"undefined"!=typeof window&&(window.WidgeticEmbedSDK=ee,window.Widgetic={SDK:ee,getSDK:b,EmbedSDK:T,config:{API_URL:P.API_URL,API_VERSION:P.API_VERSION,CLIENT_URL:P.CLIENT_URL,PRODUCTION_URL:P.PRODUCTION_URL,NODE_ENV:P.NODE_ENV},log:x,WidgeticWidget:q,registerWidgeticWidget:Q,cssDebugger:y,enableCSSDebug:()=>y.enableDebugMode(),disableCSSDebug:()=>y.disableDebugMode(),analyzeWidget:e=>y.analyzeWidget(e),ABTestManager:K,ABTestElement:J,TranslationElement:Z});export{J as ABTestElement,K as ABTestManager,T as EmbedSDK,Z as TranslationElement,T as WidgeticEmbedSDK,q as WidgeticWidget,P as config,y as cssDebugger,ee as default,$ as generateInstanceId,D as getAuthToken,b as getSDK,x as log,Q as registerWidgeticWidget};
|
|
1
|
+
import{j as n,k as r,i as l,G as w,l as b,m as T,n as D,E as _}from"./chunks/api.js";export{B as BatchApiClient,C as CSSDebugger,H as HighLevelAPI,L as LowLevelAPI,M as MidLevelAPI,o as ModuleLoader,p as analyzeWidgetCSS,q as disableCSSDebug,t as enableCSSDebug,g as getBatchClient,a as getModuleLoader,u as monitorWidgetCSS,v as resetBatchClient,x as resetModuleLoader,y as sendWorkflowEvent}from"./chunks/api.js";import{l as R,g as O,C as W,V as N,u as z,e as P,t as Q,a as K,T as U,d as V}from"./chunks/core.js";export{v as AuthError,A as AuthManager,j as DefaultTokenProvider,E as EndpointTokenProvider,F as FunctionTokenProvider,S as StaticApiKeyProvider,m as getApiUrl,x as getAuthManager,c as getCdnUrl,h as getConfiguration,k as getTokenProvider,i as setApiKey,s as setTokenProvider}from"./chunks/core.js";import{e as $,W as G}from"./chunks/renderers.js";export{C as CustomElementRenderer,I as IframeRenderer,f as WidgetRenderer,g as getWidgetRenderer,i as resetWidgetRenderer}from"./chunks/renderers.js";export{WidgeticMessenger,getMessenger,resetMessenger}from"./chunks/messaging.js";import{ABTestManager as Y}from"./chunks/ABTestManager.js";import{_ as J}from"./chunks/vendor.js";import{k as X}from"./chunks/scanner.js";export{e as detectBrowserCapabilities,j as determineBestRenderMode,f 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/display.js";import"./chunks/performance.js";import"./chunks/security.js";class Z{constructor(e){this.deviceDetector=n(),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(),R.debug("[AnalyticsTracker] Initialized",{compositionId:this.config.compositionId,sessionId:this.sessionId})}static getInstance(e){if(!Z.instance&&e&&(Z.instance=new Z(e)),!Z.instance)throw new Error("AnalyticsTracker must be initialized with config first");return Z.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){R.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){R.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?(R.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(),R.debug("[AnalyticsTracker] Event queued",{eventType:e.eventType,queueSize:this.eventQueue.length})):R.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 J(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(),R.debug("[AnalyticsTracker] Batch sent successfully",{batchSize:e.length,remainingQueue:this.eventQueue.length})}catch(t){R.error("[AnalyticsTracker] Failed to send batch",{error:t,batchSize:e.length}),this.eventQueue.unshift(...e),setTimeout((()=>this.processBatch()),5e3)}}))}sendEventBatch(e){return J(this,void 0,void 0,(function*(){if(!this.config.apiEndpoint)return void R.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 O(),n=new W({basePath:this.config.apiEndpoint,accessToken:()=>J(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${N}`}}),s=new z(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){R.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||[],R.debug("[AnalyticsTracker] Loaded queued events from storage",{count:this.eventQueue.length})):localStorage.removeItem(this.STORAGE_KEY)}}catch(e){R.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),R.debug("[AnalyticsTracker] Configuration updated",e)}clearQueue(){this.eventQueue=[],this.config.enableLocalStorage&&localStorage.removeItem(this.STORAGE_KEY),R.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)),Z.instance=null,R.debug("[AnalyticsTracker] Destroyed")}}const ee="undefined"!=typeof HTMLElement?HTMLElement:class{};class te extends ee{constructor(){super(),this.experimentId=null,this.assignment=null,this.widgetInstance=null,this.impressionTracked=!1,this.conversionListeners=new Map,this.manager=Y.getInstance(),this.widgetManager=r.getInstance(),this.analyticsTracker=Z.getInstance(),this.attachShadow({mode:"open"}),this.setupEventListeners()}static get observedAttributes(){return["experiment-id","user-id","session-id"]}connectedCallback(){return J(this,void 0,void 0,(function*(){try{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return P.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 P.warn("No variant assignment received",{experimentId:this.experimentId}),void this.renderError("Test not available");this.setupGoalListeners(),yield this.renderVariant(),yield this.trackImpression(),this.setupConversionTracking(),P.info("A/B test element initialized",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){P.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 J(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){P.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 P.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 P.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(),P.debug("Conversion tracking setup complete",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){P.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?Q(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&&!Q(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&&!Q(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=l(e))||void 0===t||t.sendAbGoal({metric:i,goalTarget:this.assignment.goalTarget||null})}catch(e){P.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(w);this.manager.setWidgetReportsGoals(this.experimentId,n),this.assignment.goalTarget&&!n&&P.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 J(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}),P.debug("Impression tracked",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){P.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;P.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;P.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){P.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",te))}}te.register();const ie="undefined"!=typeof HTMLElement?HTMLElement:class{};class ne extends ie{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=b(),R.debug("[TranslationElement] Created translation element")}connectedCallback(){if(this.isInitialized)R.debug("[TranslationElement] Already initialized, skipping");else{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return R.error("[TranslationElement] Missing experiment-id attribute"),void this.displayError("Missing experiment-id attribute");R.debug(`[TranslationElement] Connected with experiment ID: ${this.experimentId}`),this.initializeTranslation()}}disconnectedCallback(){R.debug("[TranslationElement] Disconnected"),this.cleanup()}initializeTranslation(){return J(this,void 0,void 0,(function*(){try{this.isInitialized=!0;const e=this.detectBrowserLanguages();if(R.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),R.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),R.info("[TranslationElement] Translation experiment loaded successfully",{experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,compositionId:t})}catch(e){R.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 J(this,void 0,void 0,(function*(){try{const t=K(),i=new W({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new U(i),s=yield n.getTranslationConfig({id:e});return(null==s?void 0:s.data)||null}catch(e){throw R.error("[TranslationElement] Error fetching translation experiment:",e),e}}))}findBestLanguageMatch(e,t){const i=Object.keys(t.languageCompositions||{}),n=t.rootLanguage||"en";R.debug("[TranslationElement] Available languages:",i),R.debug("[TranslationElement] Root language:",n);for(const t of e)if(i.includes(t))return R.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 R.debug("[TranslationElement] Found base language match:",n),this.trackFallbackUsage(t,n,"language_family").catch((e=>{R.debug("[TranslationElement] Failed to track language family fallback:",e)})),n}R.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=>{R.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 J(this,void 0,void 0,(function*(){const t=X(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=>{R.warn("[TranslationElement] Failed to send analytics:",e)}))}catch(e){R.warn("[TranslationElement] Error in analytics tracking:",e)}}sendAnalytics(e){return J(this,void 0,void 0,(function*(){try{const t=K(),i=new W({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new U(i);yield n.submitTranslationAnalyticsEvent({id:this.experimentId,submitTranslationAnalyticsEventRequest:e})}catch(e){R.debug("[TranslationElement] Analytics request failed:",e)}}))}trackFallbackUsage(e,t,i){return J(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),R.debug("[TranslationElement] Fallback usage tracked:",{requested:e,selected:t,fallbackType:i})}catch(e){R.debug("[TranslationElement] Failed to track fallback usage:",e)}}))}handleInitializationError(e){return J(this,void 0,void 0,(function*(){if(this.retryCount<this.maxRetries){this.retryCount++,R.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){R.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",ne),R.info("[TranslationElement] Custom element registered")))}catch(e){R.error("[TranslationElement] Failed to register custom element:",e)}}}ne.register();const se=T();"undefined"!=typeof window&&"undefined"!=typeof customElements&&($(),te.register(),ne.register()),"undefined"!=typeof window&&(window.WidgeticEmbedSDK=se,window.Widgetic={SDK:se,getSDK:T,EmbedSDK:_,config:{API_URL:V.API_URL,API_VERSION:V.API_VERSION,CLIENT_URL:V.CLIENT_URL,PRODUCTION_URL:V.PRODUCTION_URL,NODE_ENV:V.NODE_ENV},log:R,WidgeticWidget:G,registerWidgeticWidget:$,cssDebugger:D,enableCSSDebug:()=>D.enableDebugMode(),disableCSSDebug:()=>D.disableDebugMode(),analyzeWidget:e=>D.analyzeWidget(e),ABTestManager:Y,ABTestElement:te,TranslationElement:ne});export{te as ABTestElement,Y as ABTestManager,_ as EmbedSDK,ne as TranslationElement,_ as WidgeticEmbedSDK,G as WidgeticWidget,V as config,D as cssDebugger,se as default,X as generateInstanceId,O as getAuthToken,T as getSDK,R as log,$ as registerWidgeticWidget};
|