@widgetic/embed-sdk 2.1.8 → 2.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{_ as t}from"./vendor.js";import{s as e,d as i,W as o,O as s,r as n,P as r,b as a,R as d,c as l,e as h,f as u,w as c,h as p,i as f,j as g}from"./api.js";import{r as m,l as v,q as w,w as b,t as y}from"./core.js";import{p as I,r as k,w as T,b as A}from"./renderers.js";import{r as S,s as E}from"./scanner.js";import"./media.js";import"./messaging.js";import"./advanced.js";import"./display.js";import"./performance.js";import"./security.js";const C=/^[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)H(i,e.source,e),H(o,e.target,e);return{graph:t,nodesById:e,outgoingBySource:i,incomingByTarget:o}}function H(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 M(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 L(t,e,i){return N(t,e).find((t=>t.sourcePort===i))}const F={text:["is","isNot","contains","doesNotContain","startsWith","endsWith","isEmpty","isNotEmpty"],number:["is","isNot","greaterThan","atLeast","lessThan","atMost","isEmpty","isNotEmpty"],boolean:["is","isNot"]},R=["is","isNot","contains","doesNotContain","startsWith","endsWith","greaterThan","atLeast","lessThan","atMost","isEmpty","isNotEmpty"];function j(t){return null==t||"string"==typeof t&&""===t.trim()}function P(t){return null==t?"":String(t).trim().toLowerCase()}function x(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 B=new Set(["true","yes","1","on"]),_=new Set(["false","no","0","off"]);function z(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(B.has(e))return!0;if(_.has(e))return!1}}function V(t,e){const{operator:i}=t;if("isEmpty"===i)return j(e);if("isNotEmpty"===i)return!j(e);if(!function(t,e){return F[e].includes(t)}(i,t.field.type))return!1;switch(t.field.type){case"number":return function(t,e,i){const o=x(e),s=x(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=z(e),s=z(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=P(e),s=P(i),n=j(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=>V(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},q=["seconds","minutes","hours","days","weeks"],Z=365*U.days;function G(t){return"string"==typeof t&&q.includes(t)}function J(t,e){if("after"===t.mode){const i=function(t,e){if("number"!=typeof t||!Number.isInteger(t)||t<1)return;if(!G(e))return;const i=t*U[e];return i<=Z?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 K(t,e,i){const o=J(t,e);return void 0===o?void 0:Math.max(0,o-i)}function Q(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 X(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=L(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(M(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=L(t,e.id,i?i.id:"default")}return{passedNodeIds:o,takenEdgeIds:s}}function Y(t,e,i,o={}){const s=o.index??O(t),n=s.nodesById.get(e.nodeId);if(!M(n))return{outcome:"ignored",reason:"unknown_position"};const r=[];for(const t of W(s,n.id)){if(!Q(t,i))continue;r.push(t.id);const e=X(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 tt(t,e,i){t.some((t=>i(t,e)))||t.push(e)}function et(t,e,i,o){const s=[],n=L(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&&tt(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 it(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;tt(s.inputTables,e.table,n),et(o,t.id,e.table,s.inputColumns);break;case"action":""!==e.actionId&&tt(s.actionIds,e.actionId,n);break;case"pageEvent":""!==e.name&&tt(s.pageEventNames,e.name,n);break;case"scheduled":s.schedules.push({triggerId:t.id,schedule:e.schedule})}}return s}class ot{issues=[];report(t,e){this.issues.push({code:t,severity:"error",detail:e})}}function st(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function nt(t){return"string"==typeof t&&C.test(t)?t:void 0}function rt(t,e=200){return"string"==typeof t&&t.length<=e?t:void 0}function at(t){return"text"===t||"number"===t||"boolean"===t?t:void 0}function dt(t,e,i){if(!st(t))return void i.report("malformed",e);const o=function(t,e,i){if(!st(t))return void i.report("malformed",e);const o="input"===t.kind||"event"===t.kind?t.kind:void 0,s=rt(t.name,64),n=at(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&&R.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:rt(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 lt(t,e,i){if(st(t))switch(t.kind){case"input":{const o=rt(t.table);return void 0===o&&i.report("malformed",`${e}.table`),void 0===o?void 0:{kind:"input",table:o}}case"action":{const o=rt(t.actionId);return void 0===o&&i.report("malformed",`${e}.actionId`),void 0===o?void 0:{kind:"action",actionId:o}}case"pageEvent":{const o=rt(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=st(t)?rt(t.name,64):void 0,r=st(t)?at(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(st(t)&&"after"===t.mode&&"number"==typeof t.amount&&G(t.unit)&&Number.isFinite(t.amount))return{mode:"after",amount:t.amount,unit:t.unit};if(st(t)&&"at"===t.mode){const e=rt(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 ht(t,e,i){if(!st(t))return void i.report("malformed",e);const o=nt(t.id);o||i.report("bad_id",`${e}.id`);const s=function(t){if(void 0!==t)return st(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=rt(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=lt(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(!st(t)||!Array.isArray(t.tests)||t.tests.length>100)return void i.report("malformed",e);const o=nt(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=rt(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 ot;if(!st(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=ht(t,`nodes[${o}]`,e);s&&i.push(s)}));const o=[];return t.edges.forEach(((t,i)=>{const s=function(t,e,i){if(!st(t))return void i.report("malformed",e);const o=nt(t.id),s=nt(t.source),n=nt(t.sourcePort),r=nt(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 pt(t){return`widgetic_workflow_${t}`}function ft(t){return"string"==typeof t&&ct.test(t)}function gt(t){return"number"==typeof t&&Number.isFinite(t)&&t>=0}function mt(t,e){try{b(pt(t),JSON.stringify({v:1,versionId:e.versionId,nodeId:e.nodeId,compositionId:e.compositionId,startedAt:e.startedAt,reachedAt:e.reachedAt}))}catch(e){v.debug("[workflows] The visitor's position could not be kept",{workflowId:t,error:e})}}function vt(t){w(pt(t))}const wt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,bt=/^[A-Za-z0-9_-]{1,64}$/,yt=new Set(["n","e","f"]),It=new Map([["timeout","t"],["widget_error","e"],["build","b"],["other","o"]]);function kt(t,e,i){return i?`${t}:${e}:${i}`:`${t}:${e}`}class Tt{constructor(t){this.pending=[],this.lastEventOf=new Map,this.flushTimer=null,this.waitingHeights=new Map,this.settledHeights=[],this.reportedSteps=new Set,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,o){if(this.stopped||!this.options.token)return;if(!yt.has(t)||!bt.test(e)||!Number.isInteger(i)||i<1)return;const s="f"===t&&"string"==typeof o?It.get(o):void 0,n=kt(t,e,s);let r=i;for(;r>0;){let i=this.lastEventOf.get(n);(!i||i.c>=50)&&(i=Object.assign({k:t,id:e,c:0},s?{r:s}:{}),this.pending.push(i),this.lastEventOf.set(n,i));const o=Math.min(r,50-i.c);i.c+=o,r-=o}this.pending.length>=100?this.flush():null===this.flushTimer&&(this.flushTimer=setTimeout((()=>this.flush()),2e3))}noteHeight(t,e){if(this.stopped||!this.options.token)return;if(!wt.test(t))return;if(!Number.isFinite(e))return;const i=Math.round(e);if(i<1||i>1e5)return;const o=t.toLowerCase();if(this.reportedSteps.has(o))return;const s=this.waitingHeights.get(o);(null==s?void 0:s.height)!==i&&(!s&&this.waitingHeights.size+this.reportedSteps.size>=10||(s&&clearTimeout(s.timer),this.waitingHeights.set(o,{height:i,timer:setTimeout((()=>this.settleHeight(o)),3e3)})))}flushBeforeLeaving(){if(!this.stopped&&this.options.token)for(this.settleWaitingHeights();this.pending.length>0||this.settledHeights.length>0;){const t=this.takeBatch(),e=this.takeSettledHeights();if(!this.options.isActive())return void this.forgetPending();this.sendWithBeacon(t,e)}}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=kt(e.k,e.id,e.r);this.lastEventOf.get(t)===e&&this.lastEventOf.delete(t)}return t}takeSettledHeights(){return this.settledHeights.splice(0,10)}settleHeight(t){const e=this.waitingHeights.get(t);e&&(this.waitingHeights.delete(t),this.handOver(t,e.height),this.flush())}settleWaitingHeights(){for(const[t,e]of this.waitingHeights)clearTimeout(e.timer),this.handOver(t,e.height);this.waitingHeights.clear()}handOver(t,e){this.reportedSteps.add(t),this.settledHeights.push({compositionId:t,height:e})}forgetPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.pending=[],this.lastEventOf.clear();for(const t of this.waitingHeights.values())clearTimeout(t.timer);this.waitingHeights.clear(),this.settledHeights=[]}flush(){if(null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.stopped||0===this.pending.length&&0===this.settledHeights.length)return;if(!this.options.isActive())return void this.forgetPending();const t=this.takeBatch(),e=this.takeSettledHeights();this.sendWithRequest(t,e),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,e){return JSON.stringify(Object.assign({versionId:this.options.versionId,token:this.options.token,events:t.map((t=>Object.assign(Object.assign({k:t.k,id:t.id},t.c>1?{c:t.c}:{}),t.r?{r:t.r}:{})))},e.length>0?{heights:e}:{}))}sendWithBeacon(t,e){try{const i=this.reportBody(t,e),o="undefined"!=typeof navigator?navigator.sendBeacon:void 0;if("function"==typeof o&&o.call(navigator,this.reportAddress(),new Blob([i],{type:"text/plain"})))return void v.debug("[workflows] Counts handed to the browser to send",{eventCount:t.length,heightCount:e.length})}catch(t){v.debug("[workflows] The browser would not take counts to send as the page closes",{error:t})}this.sendWithRequest(t,e)}sendWithRequest(e,i){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,i)});if(401===t.status)return v.warn("[workflows] The gateway refused the token for counts, so this embed stops reporting",{workflowId:this.options.workflowId}),void this.dispose();v.debug("[workflows] Counts sent",{eventCount:e.length,heightCount:i.length,status:t.status})}catch(t){v.debug("[workflows] Counts could not be sent and were dropped",{eventCount:e.length,heightCount:i.length,error:t})}}))}}const At=/^[a-z0-9]{1,8}(-[a-z0-9]{1,8}){0,4}$/,St=/^[A-Za-z0-9_.:-]{1,128}$/;function Et(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function Ct(t){if("string"!=typeof t||t.length>35)return null;const e=t.toLowerCase();return At.test(e)?e:null}function Ot(){var t,e;try{if("undefined"==typeof navigator)return[];const i=String(null!==(t=navigator.language)&&void 0!==t?t:"").toLowerCase(),o=((null===(e=navigator.languages)||void 0===e?void 0:e.map((t=>String(t).toLowerCase())))||[i]).flatMap((t=>{const e=[t];return t.includes("-")&&e.push(t.split("-")[0]),e}));return[...new Set(o)].filter((t=>""!==t))}catch(t){return v.debug("[workflows] The languages of the browser could not be read",{error:t}),[]}}function Ht(t,e,i){if(!e||0===i.length||!Object.prototype.hasOwnProperty.call(e,t))return t;const o=e[t],{language:s}=function(t,e){const i=Object.keys(e.compositions);for(const e of t)if(i.includes(e))return{language:e,match:"exact"};for(const e of t){const t=e.split("-")[0],o=i.find((e=>e.startsWith(`${t}-`)||e===t));if(void 0!==o)return{language:o,match:"family"}}return{language:e.rootLanguage,match:"root"}}(i,o);return s===o.rootLanguage?t:o.compositions[s]||t}const Nt=/^[A-Za-z0-9_-]{1,64}$/,Mt=/^[A-Za-z0-9_.:-]{1,128}$/;function $t(t){return Nt.test(t)}function Wt(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function Lt(t,e){var i;if(!Wt(t)||!0!==t.success||!Wt(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||!Mt.test(o.versionId))return{kind:"unreadable"};const s=ut(o.graph);if(!s.graph||s.issues.length>0)return v.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};"number"==typeof o.versionNumber&&Number.isInteger(o.versionNumber)&&(n.versionNumber=o.versionNumber),"string"==typeof o.publishedAt&&(n.publishedAt=o.publishedAt),"string"==typeof o.startCompositionId&&Mt.test(o.startCompositionId)&&(n.startCompositionId=o.startCompositionId);const r=function(t){if(!Et(t))return;const e=Object.create(null);let i=0;for(const[o,s]of Object.entries(t)){if(i>=64)break;if(!St.test(o)||!Et(s))continue;const t=Ct(s.rootLanguage);if(null===t||!Et(s.compositions))continue;const n=Object.create(null);let r=0;for(const[t,e]of Object.entries(s.compositions)){if(r>=128)break;const i=Ct(t);null!==i&&"string"==typeof e&&St.test(e)&&(n[i]=e,r+=1)}0!==r&&(e[o]={rootLanguage:t,compositions:n},i+=1)}return 0===i?void 0:e}(o.translations);return r&&(n.translations=r),"string"==typeof o.eventToken&&""!==o.eventToken&&o.eventToken.length<=2048&&(n.eventToken=o.eventToken),{kind:"live",workflow:n}}function Ft(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=Lt(s,i);return"live"===n.kind?{kind:"live",workflow:n.workflow}:n}catch(t){return v.debug("[workflows] A host could not be reached",{workflowId:i,error:t}),{kind:"unreachable"}}finally{clearTimeout(o)}}))}const Rt=new Map;function jt(e,i={}){var o,s;if(!$t(e)||void 0!==i.versionId&&!Mt.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=Rt.get(n);if(r)return r;const a=function(e,i){return t(this,void 0,void 0,(function*(){var t;const o=null!==(t=i.origins)&&void 0!==t?t:I(),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 Ft(`${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 a=n?"not_found":r?"unreadable":"unreachable";return v.debug("[workflows] The workflow is not available",{workflowId:e,reason:a}),{status:"unavailable",reason:a}}))}(e,i);return Rt.set(n,a),a.finally((()=>{Rt.get(n)===a&&Rt.delete(n)})),a}const Pt={clicks:"click",submissions:"submit",plays:"play"},xt=new Set(["__proto__","constructor","prototype"]);function Bt(t){const e=t.detail;return"object"!=typeof e||null===e||Array.isArray(e)?{}:e}function _t(t,e){return("submissions"!==t.metric||"FORM"===e.tagName)&&(("plays"!==t.metric||"VIDEO"===e.tagName||"AUDIO"===e.tagName)&&(null!==t.selector?y(e,t.selector):"clicks"!==t.metric||null!==e.closest('button, a, input[type="button"], input[type="submit"], [role="button"], [onclick], [data-click-track]')))}function zt({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 a=new Set,d=t=>{var s;if(n)return;const r=Bt(t),d=r.table;if("string"!=typeof d||!i.inputTables.includes(d))return;if("string"==typeof r.entryId&&""!==r.entryId){const t=`${d}:${r.entryId}`;if(a.has(t))return;if(a.add(t),a.size>100){const t=a.values().next().value;void 0!==t&&a.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(xt.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(d))&&void 0!==s?s:new Set);v.debug("[workflows] An entry was saved in a watched table",{table:d,valueCount:Object.keys(l).length}),o([{type:"input",table:d,values:l}])};t.addEventListener("widgetic:submitted",d),r.push((()=>t.removeEventListener("widgetic:submitted",d)))}if(i.actionIds.length>0){const s=t=>{if(n)return;const e=Bt(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)&&(v.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 d=[];for(const t of i.actionIds){const i=e(t);i&&(a=i.metric,Object.prototype.hasOwnProperty.call(Pt,a))&&d.push({actionId:t,metric:i.metric,selector:i.selector})}if(d.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 d)Pt[o.metric]===t.type&&_t(o,e)&&i.push({type:"action",actionId:o.actionId});return i},a=t=>{if(n)return;const e=s(t);0!==e.length&&(v.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(d.map((t=>Pt[t.metric])));for(const t of r)n.addEventListener(t,a,!0);e=n,i=()=>{for(const t of r)n.removeEventListener(t,a,!0);e=null,i=()=>{}}};t.addEventListener("widgetic:ready",l),r.push((()=>t.removeEventListener("widgetic:ready",l))),r.push((()=>i())),l()}}var a;return{stop:()=>{if(!n){n=!0;for(const t of r)try{t()}catch(t){v.debug("[workflows] A listener could not be removed",{error:t})}}}}}const Vt=50,Dt=2e3,Ut=150,qt=5,Zt=300,Gt=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 Kt(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 Qt(t,e,i){return null===t||e!==t&&Math.abs(e-t)>=i}const Xt=o,Yt=["width","height","resize","resize-mode","render-mode","use-iframe","theme","mode","colors","sandbox","autoload","adaptive","responsive"],te=["values","context","media-resolver"],ee=["design","content","content-items","contentitems","items"];function ie(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 v.debug("[workflows] The browser could not watch heights",{error:t}),null}}function oe(t){return t.getBoundingClientRect().height}function se(){try{return"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch(t){return!1}}function ne(t){return"number"==typeof t&&Number.isFinite(t)&&t>0}class re{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.firstVisitStage=null,this.firstVisitStageIsReady=!1,this.host=t.host,this.services=t.services,this.prefersReducedMotion=null!==(e=t.prefersReducedMotion)&&void 0!==e?e:se,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}currentCompositionId(){var t,e;return null!==(e=null===(t=this.current)||void 0===t?void 0:t.compositionId)&&void 0!==e?e:null}showFirstStage(t,e=t){if(this.current)return{stage:this.current.element,ready:Promise.resolve({status:"ready"})};this.viewportElement.isConnected||this.host.appendChild(this.viewportElement);const i=this.holdRoomFor(t),o=this.buildStage(t,!0,e);this.current=o,this.firstVisitStage=i||t!==e?null:o;const s=this.waitUntilShown(o,null,(t=>{if("ready"===t.status&&this.firstVisitStage===o&&(this.firstVisitStageIsReady=!0),"ready"===t.status&&!this.destroyed&&this.autoscaleOn&&this.current===o){const t=this.measure(o.element);ne(t)&&this.applyHeight(t,"immediate")}}));return this.viewportElement.appendChild(o.element),this.services.hydrate(o.element),{stage:o.element,ready:s}}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:ie)((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);ne(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,arguments,void 0,(function*(t,e=t){var o,s,n;if(this.destroyed)return{status:"failed",reason:"stopped"};if(this.incoming)return{status:"failed",reason:"busy"};this.enableAutoscale();const r=this.buildStage(t,!1,e);this.incoming=r,this.hideBeside(r.element);const a=this.waitUntilShown(r,null!==(o=this.services.readyTimeoutMilliseconds)&&void 0!==o?o:8e3);this.viewportElement.appendChild(r.element),this.services.hydrate(r.element);const d=yield a;if(this.destroyed)return{status:"failed",reason:"stopped"};if(this.incoming=null,"failed"===d.status)return this.removeStage(r),"timeout"===d.reason&&i(this.host,t,"workflow_step_timeout"),v.debug("[workflows] The next composition could not be shown, so the visitor stays where they are",{compositionId:t,reason:d.reason}),Object.assign({status:"failed",reason:"stopped"===d.reason?"stopped":d.reason},d.code?{code:d.code}:{});const l=this.current;this.revealInPlace(r.element),this.current=r,null===(s=this.heightObserver)||void 0===s||s.observe(r.element);const h=this.measure(r.element);return ne(h)&&this.applyHeight(h,"immediate"),l&&(null===(n=this.heightObserver)||void 0===n||n.unobserve(l.element),this.removeStage(l)),{status:"shown",stage:r.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,i){var o,s,n;const r=document.createElement("widgetic");r.setAttribute("composition-id",t),r.setAttribute(Xt,"1"),r.style.display="block";for(const t of Yt){const e=this.host.getAttribute(t);null!==e&&r.setAttribute(t,e)}this.widthOverride&&r.setAttribute("width",this.widthOverride);for(const t of te){const e=this.host.getAttribute(t);null!==e&&r.setAttribute(t,e)}const a=i===(null!==(o=this.host.getAttribute("composition-id"))&&void 0!==o?o:"").trim();a&&this.copyWhatThePageWroteForTheTagComposition(r);const d={element:r,compositionId:t,standsFor:i,reportedHeight:!1,cancelWait:null,stopListening:()=>{}},l=t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.height;if("number"!=typeof i||!ne(i))return;const o=r.querySelector("iframe");o&&(o.style.height=`${Math.ceil(i)}px`,d.reportedHeight=!0)};r.addEventListener("widgetic:resize",l),d.stopListening=()=>r.removeEventListener("widgetic:resize",l);try{null===(n=(s=this.services).onStageCreated)||void 0===n||n.call(s,r,{compositionId:t,standsFor:i,isFirst:e,carriesPageContent:a})}catch(e){v.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))S(e.name)||t.setAttribute(e.name,e.value);for(const e of ee){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&&te.includes(null!==(e=t.attributeName)&&void 0!==e?e:"")}))&&this.mirrorAttributesToStages()})),this.attributeObserver.observe(this.host,{attributes:!0,attributeFilter:[...te]})}catch(t){this.attributeObserver=null,v.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 te){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 a=e=>{if(!r){r=!0,null!==n&&clearTimeout(n),s.removeEventListener("widgetic:ready",d),s.removeEventListener("widgetic:error",l),s.removeEventListener("load",h,!0),t.cancelWait=null;try{null==i||i(e)}catch(e){v.debug("[workflows] A stage could not be settled",{compositionId:t.compositionId,error:e})}o(e)}},d=()=>a({status:"ready"}),l=t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.code;a(Object.assign({status:"failed",reason:"error"},"string"==typeof i?{code:i}:{}))},h=t=>{t.target instanceof HTMLIFrameElement&&a({status:"ready"})};s.addEventListener("widgetic:ready",d),s.addEventListener("widgetic:error",l),s.addEventListener("load",h,!0),t.cancelWait=()=>a({status:"failed",reason:"stopped"}),null!==e&&(n=setTimeout((()=>a({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){v.debug("[workflows] A listener for a removed stage failed",{compositionId:t.compositionId,error:e})}}noteFrameWithoutHeight(t){this.warnedAboutFrameWithoutHeight||(this.warnedAboutFrameWithoutHeight=!0,v.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:oe)(t)}catch(t){return v.debug("[workflows] The height of a stage could not be read",{error:t}),0}}holdRoomFor(t){const e=k(t);if(null===e)return!1;const i=this.settings();return this.viewportElement.style.minHeight=`${Kt(e,i,this.overlayCap())}px`,!0}settings(){return function(t,e={}){const i=Jt(t,"autoscale-min-height",Vt,Gt),o=Jt(t,"autoscale-max-height",Dt,Gt);return{minHeight:i,maxHeight:Math.max(o,i),debounceDelay:Jt(t,"autoscale-debounce",Ut,5e3),threshold:Jt(t,"autoscale-threshold",qt,Gt),animate:"false"!==t.getAttribute("autoscale-animate")&&!0!==e.prefersReducedMotion,animationDuration:Jt(t,"autoscale-animation-duration",Zt,5e3)}}(this.host,{prefersReducedMotion:this.prefersReducedMotion()})}overlayCap(){return this.host.hasAttribute(s)?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&&ne(e.height)&&this.applyHeight(e.height,"observed")}applyHeight(t,e){this.tellFirstVisitHeight(t);const i=this.settings(),o=Kt(t,i,this.overlayCap());if("immediate"===e)return this.clearHeightTimer(),void this.setHeight(o,i);Qt(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();Qt(this.appliedHeight,t,e.threshold)&&this.setHeight(t,e)}),i.debounceDelay)):o===this.appliedHeight&&this.clearHeightTimer()}tellFirstVisitHeight(t){var e,i;const o=this.current;if(o&&o===this.firstVisitStage&&this.firstVisitStageIsReady&&!this.host.hasAttribute(s)&&(!o.element.querySelector("iframe")||o.reportedHeight))try{null===(i=(e=this.services).onFirstStageHeight)||void 0===i||i.call(e,o.standsFor,Math.ceil(t))}catch(t){v.debug("[workflows] A listener for the height of the first stage failed",{compositionId:o.compositionId,error:t})}}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);T(this.current.compositionId,t,Number.isFinite(e)?e:t)}}clearHeightTimer(){null!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingHeight=null}}const ae=3e4,de=2e3;function le(t,e){return e?"build":"timeout"===t.reason?"timeout":"error"===t.reason?"widget_error":"other"}function he(t,e,i){var o;try{p(t,f(e,i)),null===(o=g(t))||void 0===o||o.sendWorkflowWatch(i)}catch(t){v.debug("[workflows] A widget could not be told what to report",{compositionId:e,error:t})}}function ue(t){try{A(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){v.debug("[workflows] A composition could not be got ready",{compositionId:t,error:e})}}function ce(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 pe{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 r,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.hostIsMarkedMounted=!1,this.copiesThatCannotBeShown=new Set,this.cancelWaitForAnswer=null,this.onPageEvent=t=>{if("ended"===this.mode||"plain"===this.mode)return;const e=a(t.detail);e?"running"!==this.mode||this.stepping?this.pageEvents.add(e):this.hasEnded()||this.react([{type:"pageEvent",name:e.name,values:e.values}]):v.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()},this.visitorLanguages=this.readVisitorLanguages();const n=s.viewport;this.viewport=new re(Object.assign(Object.assign(Object.assign({host:t},n.prefersReducedMotion?{prefersReducedMotion:n.prefersReducedMotion}:{}),o.width?{widthOverride:o.width}:{}),{services:Object.assign(Object.assign(Object.assign(Object.assign({hydrate:o.hydrate},n.createHeightObserver?{createHeightObserver:n.createHeightObserver}:{}),n.measureStageHeight?{measureStageHeight:n.measureStageHeight}:{}),void 0!==n.readyTimeoutMilliseconds?{readyTimeoutMilliseconds:n.readyTimeoutMilliseconds}:{}),{onStageCreated:(t,e)=>this.onStageCreated(t,e.compositionId),onStageRemoved:t=>this.onStageRemoved(t),onFirstStageHeight:(t,e)=>{var i;return null===(i=this.counts)||void 0===i?void 0:i.noteHeight(t,e)}})}))}readVisitorLanguages(){try{const t=this.services.visitorLanguages();return Array.isArray(t)?t.filter((t=>"string"==typeof t)):[]}catch(t){return v.debug("[workflows] The languages of the visitor could not be read",{error:t}),[]}}start(){var t;const e=function(t,e=Date.now()){const i=pt(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)&&gt(s.startedAt)&&gt(s.reachedAt)?s.startedAt>e+864e5?null:e-s.startedAt>2592e6?(vt(t),v.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 v.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(),this.displayBeforeMounting=this.host.style.display,this.run(e,i)}run(e,i){return t(this,void 0,void 0,(function*(){var t;try{const o=this.services.fetchWorkflow(this.workflowId);this.readiedCompositions.add(i),this.services.prefetchComposition(i);const s=yield this.waitForAnswer(o);if(this.hasEnded())return;const n=this.compositionToShow("live"===(null==s?void 0:s.status)?s.workflow:null,i),r=this.showFirstComposition(n,i),[a,d]=yield Promise.all([o,r]);if(this.hasEnded())return;let l=d;if("failed"===l.status&&"stopped"!==l.reason&&n!==i&&(l=yield this.fallBackToTheComposition(n,i),this.hasEnded()))return;let h=e,u=i;if("failed"===l.status){if("stopped"===l.reason)return;if(!e||e.compositionId===this.tagCompositionId)return void this.refuse(l.code);{v.debug("[workflows] The composition a returning visitor was on cannot be shown, so they start again",{compositionId:e.compositionId}),vt(this.workflowId),h=null;const i=yield this.swapToComposition(this.tagCompositionId,"live"===a.status?a.workflow:null);if(this.hasEnded())return;if("shown"!==i.status)return void this.refuse(null!==(t=l.code)&&void 0!==t?t:"failed"===i.status?i.code:void 0);u=this.tagCompositionId}}if("live"!==a.status)return v.debug("[workflows] The workflow is not running, so the tag is a plain embed",{workflowId:this.workflowId,status:a.status}),void(yield this.becomePlain());let c=a.workflow,p=a.origin;if(h&&h.versionId!==c.versionId){const t=yield this.services.fetchWorkflow(this.workflowId,{versionId:h.versionId});if(this.hasEnded())return;"live"===t.status&&t.workflow.versionId===h.versionId?(c=t.workflow,p=t.origin):(v.debug("[workflows] The version a visitor started on cannot be read, so they continue as a new visitor",{versionId:h.versionId}),vt(this.workflowId),h=null)}const f=O(c.graph);let g=h&&this.fitsTheGraph(h,c,f)?h:null;const m=null===g;if(null===g){h&&(v.debug("[workflows] The place a visitor was kept at is not in the workflow, so they continue as a new visitor"),vt(this.workflowId));const t=function(t,e){for(const i of t.nodes)if("composition"===i.type&&i.compositionId===e)return i}(c.graph,this.tagCompositionId);if(!t)return v.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());const e=Date.now();g={versionId:c.versionId,nodeId:t.id,compositionId:this.tagCompositionId,startedAt:e,reachedAt:e}}const w=yield this.showThePlace(g.compositionId,c,u);if(this.hasEnded())return;if("plain"===w)return void(yield this.becomePlain());this.activate(c,p,f,g,m)}catch(t){v.warn("[workflows] The workflow stopped working, so the tag stays as it is",{workflowId:this.workflowId,error:t}),this.becomePlainWithoutWaiting(),this.makeSureTheTagCompositionIsShown()}}))}waitForAnswer(t){const e=this.services.firstCompositionWaitMilliseconds;return new Promise(((i,o)=>{let s=null;const n=t=>{null!==s&&clearTimeout(s),s=null,this.cancelWaitForAnswer=null,i(t)};this.cancelWaitForAnswer=()=>n(null),s=setTimeout((()=>n(null)),Number.isFinite(e)?Math.max(0,e):0),t.then(n,(t=>{null!==s&&clearTimeout(s),s=null,this.cancelWaitForAnswer=null,o(t)}))}))}showFirstComposition(t,e){t!==e&&v.debug("[workflows] A composition is shown in the visitor's language",{compositionId:e,copyId:t});const{ready:i}=this.viewport.showFirstStage(t,e);return this.markHostMounted(),i}markHostMounted(){this.hostIsMarkedMounted||(this.hostIsMarkedMounted=!0,this.options.markMounted(this.host))}makeSureTheTagCompositionIsShown(){if("ended"!==this.mode&&null===this.viewport.currentStage())try{this.viewport.showFirstStage(this.tagCompositionId),this.markHostMounted()}catch(t){v.debug("[workflows] The composition of the tag could not be shown",{error:t})}}compositionToShow(t,e){if(!t)return e;const i=Ht(e,t.translations,this.visitorLanguages);return this.copiesThatCannotBeShown.has(i)?e:i}noteThatTheCopyCannotBeShown(t,e){this.copiesThatCannotBeShown.has(t)||(this.copiesThatCannotBeShown.add(t),v.debug("[workflows] The copy of a composition in the visitor's language cannot be shown, so the composition itself is",{compositionId:e,copyId:t}))}fallBackToTheComposition(e,i){return t(this,void 0,void 0,(function*(){this.noteThatTheCopyCannotBeShown(e,i);const t=yield this.viewport.swapTo(i);return"shown"===t.status?{status:"ready"}:Object.assign({status:"failed",reason:"busy"===t.reason?"error":t.reason},t.code?{code:t.code}:{})}))}swapToComposition(e,i){return t(this,void 0,void 0,(function*(){const t=this.compositionToShow(i,e);t!==e&&v.debug("[workflows] A composition is shown in the visitor's language",{compositionId:e,copyId:t});const o=yield this.viewport.swapTo(t,e);return"shown"===o.status||t===e||"stopped"===o.reason||"busy"===o.reason?o:this.hasEnded()?{status:"failed",reason:"stopped"}:(this.noteThatTheCopyCannotBeShown(t,e),this.viewport.swapTo(e))}))}showThePlace(e,i,o){return t(this,void 0,void 0,(function*(){const t=this.compositionToShow(i,e);if(o===e&&this.viewport.currentCompositionId()===t)return"shown";return"shown"===(yield this.swapToComposition(e,i)).status||o===e?"shown":"plain"}))}fitsTheGraph(t,e,i){if(t.versionId!==e.versionId)return!1;const o=i.nodesById.get(t.nodeId);return M(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)),v.debug("[workflows] The workflow runs",{workflowId:this.workflowId,versionId:t.versionId,isNewVisitor:s}),this.viewport.enableAutoscale();const a=this.viewport.currentStage();a&&this.armStage(a,o.nodeId),this.armSchedules(),this.getNextCompositionsReady(),this.drainPageEvents()}becomePlain(){return t(this,void 0,void 0,(function*(){if(this.mode="plain",this.pageEvents.clear(),this.viewport.currentCompositionId()!==this.tagCompositionId){const t=yield this.viewport.swapTo(this.tagCompositionId);if(this.hasEnded())return;"shown"!==t.status&&v.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),v.debug("[workflows] The composition of the tag cannot be shown",{workflowId:this.workflowId,reason:i})}listenToThePage(){this.host.addEventListener(l,this.onPageEvent),document.addEventListener("visibilitychange",this.onVisibilityChange),this.removeListeners.push((()=>this.host.removeEventListener(l,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,e){this.stages.set(t,{compositionId:e,signals:null,stopWatchingReady:null}),null!==this.pendingStageNodeId&&this.armStage(t,this.pendingStageNodeId)}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 a=r.nodesById.get(e);if(!M(a))return;const d=null!==(i=this.stages.get(t))&&void 0!==i?i:{compositionId:a.compositionId,signals:null,stopWatchingReady:null};null===(o=d.signals)||void 0===o||o.stop(),null===(s=d.stopWatchingReady)||void 0===s||s.call(d),this.stages.set(t,d);const l=it(n.graph,e,{index:r});d.signals=zt({stage:t,watch:l,emit:e=>this.onSignals(t,e)});const u=h(l);if(0===u.tables.length&&0===u.fields.length&&0===u.goals.length)return;const c=()=>this.services.deliverWatch(t,d.compositionId,u);c(),t.addEventListener("widgetic:ready",c),d.stopWatchingReady=()=>t.removeEventListener("widgetic:ready",c)}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=Y(e.graph,{nodeId:o.nodeId},s,{index:i})}catch(t){v.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(!M(s))return;let n;this.stepping=!0,this.cancelRetry(),this.cancelSchedules(),this.pendingStageNodeId=s.id;let r=!1;try{n=yield this.swapToComposition(s.compositionId,this.workflow)}catch(t){v.debug("[workflows] The next composition could not be built",{compositionId:s.compositionId,error:t}),r=!0,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,le(n,r)))}))}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),v.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,s){var n;null===(n=this.counts)||void 0===n||n.count("f",e.id,1,s),v.debug("[workflows] The next composition could not be shown, so the visitor stays where they are",{compositionId:e.compositionId,isRetry:o,reason:s}),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 it(t.graph,i.nodeId,{index:e}).schedules){const t=K(s,i.reachedAt,Date.now());void 0!==t?this.waitFor(o,s,i.nodeId,t):v.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=K(e,o.reachedAt,Date.now());void 0!==n&&(n>0?this.waitFor(t,e,i,n):(v.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)){const i=this.compositionToShow(this.workflow,t);if(!this.readiedCompositions.has(i)){if(e>=5)break;this.readiedCompositions.add(i),e+=1,this.services.prefetchComposition(i)}}})))}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);M(s)?i.includes(s.compositionId)||i.push(s.compositionId):$(s)&&t.push(s.id)}}}}return i}hasEnded(){return"ended"===this.mode||!this.host.isConnected&&(v.debug("[workflows] The tag left the page, so its workflow ends",{workflowId:this.workflowId}),this.stop(),!0)}stop(){var t,e,i,o,s,n;if("ended"!==this.mode){try{null===(t=this.counts)||void 0===t||t.flushBeforeLeaving()}catch(t){v.debug("[workflows] The last counts could not be sent",{error:t})}this.mode="ended",null===(e=this.cancelWaitForAnswer)||void 0===e||e.call(this),this.cancelRetry(),this.cancelSchedules(),null===(i=this.cancelIdleWork)||void 0===i||i.call(this),this.cancelIdleWork=null;for(const t of this.removeListeners.splice(0))t();for(const t of this.stages.values())null===(o=t.signals)||void 0===o||o.stop(),null===(s=t.stopWatchingReady)||void 0===s||s.call(t);this.stages.clear(),this.pageEvents.clear();try{null===(n=this.counts)||void 0===n||n.dispose()}catch(t){v.debug("[workflows] The counts could not be closed",{error:t})}this.viewport.destroy()}}}function fe(t,e){var i,o,s;const r=(null!==(i=t.getAttribute("workflow-id"))&&void 0!==i?i:"").trim(),a=(null!==(o=t.getAttribute("composition-id"))&&void 0!==o?o:"").trim();if(!$t(r)||""===a)return v.debug("[workflows] The tag is not a workflow embed, so it is embedded as it is",{workflowId:r,tagCompositionId:a}),null;const d={fetchWorkflow:jt,createCounts:t=>new Tt(t),deliverWatch:he,prefetchComposition:ue,whenIdle:ce,visitorLanguages:Ot,firstCompositionWaitMilliseconds:2e3,viewport:{}},l=Object.assign(Object.assign(Object.assign({},d),e.services),{viewport:Object.assign(Object.assign({},d.viewport),null===(s=e.services)||void 0===s?void 0:s.viewport)}),h=new pe(t,r,a,e,l);try{h.start()}catch(t){return v.warn("[workflows] The workflow could not start, so the tag is embedded as it is",{workflowId:r,error:t}),h.stop(),null}const u={stop:()=>h.stop()};return n(t,u),u}export{de as FIRST_COMPOSITION_WAIT_MILLISECONDS,ae as RETRY_AFTER_FAILED_STEP_MILLISECONDS,le as failureReasonOf,fe as startWorkflowEmbed};
1
+ import{_ as t}from"./vendor.js";import{s as e,d as i,W as o,O as s,r as n,P as r,b as a,R as d,c as l,e as h,f as u,w as c,h as f,i as p,j as g}from"./api.js";import{r as m,l as v,q as w,w as b,t as y}from"./core.js";import{p as I,r as k,w as T,b as A}from"./renderers.js";import{x as S,y as E}from"./scanner.js";import"./media.js";import"./messaging.js";import"./advanced.js";import"./display.js";import"./performance.js";import"./security.js";const C=/^[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)H(i,e.source,e),H(o,e.target,e);return{graph:t,nodesById:e,outgoingBySource:i,incomingByTarget:o}}function H(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 M(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 L(t,e,i){return N(t,e).find((t=>t.sourcePort===i))}const F={text:["is","isNot","contains","doesNotContain","startsWith","endsWith","isEmpty","isNotEmpty"],number:["is","isNot","greaterThan","atLeast","lessThan","atMost","isEmpty","isNotEmpty"],boolean:["is","isNot"]},R=["is","isNot","contains","doesNotContain","startsWith","endsWith","greaterThan","atLeast","lessThan","atMost","isEmpty","isNotEmpty"];function j(t){return null==t||"string"==typeof t&&""===t.trim()}function P(t){return null==t?"":String(t).trim().toLowerCase()}function x(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 B=new Set(["true","yes","1","on"]),_=new Set(["false","no","0","off"]);function z(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(B.has(e))return!0;if(_.has(e))return!1}}function V(t,e){const{operator:i}=t;if("isEmpty"===i)return j(e);if("isNotEmpty"===i)return!j(e);if(!function(t,e){return F[e].includes(t)}(i,t.field.type))return!1;switch(t.field.type){case"number":return function(t,e,i){const o=x(e),s=x(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=z(e),s=z(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=P(e),s=P(i),n=j(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=>V(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},q=["seconds","minutes","hours","days","weeks"],Z=365*U.days;function G(t){return"string"==typeof t&&q.includes(t)}function J(t,e){if("after"===t.mode){const i=function(t,e){if("number"!=typeof t||!Number.isInteger(t)||t<1)return;if(!G(e))return;const i=t*U[e];return i<=Z?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 K(t,e,i){const o=J(t,e);return void 0===o?void 0:Math.max(0,o-i)}function Q(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 X(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=L(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(M(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=L(t,e.id,i?i.id:"default")}return{passedNodeIds:o,takenEdgeIds:s}}function Y(t,e,i,o={}){const s=o.index??O(t),n=s.nodesById.get(e.nodeId);if(!M(n))return{outcome:"ignored",reason:"unknown_position"};const r=[];for(const t of W(s,n.id)){if(!Q(t,i))continue;r.push(t.id);const e=X(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 tt(t,e,i){t.some((t=>i(t,e)))||t.push(e)}function et(t,e,i,o){const s=[],n=L(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&&tt(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 it(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;tt(s.inputTables,e.table,n),et(o,t.id,e.table,s.inputColumns);break;case"action":""!==e.actionId&&tt(s.actionIds,e.actionId,n);break;case"pageEvent":""!==e.name&&tt(s.pageEventNames,e.name,n);break;case"scheduled":s.schedules.push({triggerId:t.id,schedule:e.schedule})}}return s}class ot{issues=[];report(t,e){this.issues.push({code:t,severity:"error",detail:e})}}function st(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function nt(t){return"string"==typeof t&&C.test(t)?t:void 0}function rt(t,e=200){return"string"==typeof t&&t.length<=e?t:void 0}function at(t){return"text"===t||"number"===t||"boolean"===t?t:void 0}function dt(t,e,i){if(!st(t))return void i.report("malformed",e);const o=function(t,e,i){if(!st(t))return void i.report("malformed",e);const o="input"===t.kind||"event"===t.kind?t.kind:void 0,s=rt(t.name,64),n=at(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&&R.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:rt(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 lt(t,e,i){if(st(t))switch(t.kind){case"input":{const o=rt(t.table);return void 0===o&&i.report("malformed",`${e}.table`),void 0===o?void 0:{kind:"input",table:o}}case"action":{const o=rt(t.actionId);return void 0===o&&i.report("malformed",`${e}.actionId`),void 0===o?void 0:{kind:"action",actionId:o}}case"pageEvent":{const o=rt(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=st(t)?rt(t.name,64):void 0,r=st(t)?at(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(st(t)&&"after"===t.mode&&"number"==typeof t.amount&&G(t.unit)&&Number.isFinite(t.amount))return{mode:"after",amount:t.amount,unit:t.unit};if(st(t)&&"at"===t.mode){const e=rt(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 ht(t,e,i){if(!st(t))return void i.report("malformed",e);const o=nt(t.id);o||i.report("bad_id",`${e}.id`);const s=function(t){if(void 0!==t)return st(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=rt(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=lt(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(!st(t)||!Array.isArray(t.tests)||t.tests.length>100)return void i.report("malformed",e);const o=nt(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=rt(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 ot;if(!st(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=ht(t,`nodes[${o}]`,e);s&&i.push(s)}));const o=[];return t.edges.forEach(((t,i)=>{const s=function(t,e,i){if(!st(t))return void i.report("malformed",e);const o=nt(t.id),s=nt(t.source),n=nt(t.sourcePort),r=nt(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 ft(t){return`widgetic_workflow_${t}`}function pt(t){return"string"==typeof t&&ct.test(t)}function gt(t){return"number"==typeof t&&Number.isFinite(t)&&t>=0}function mt(t,e){try{b(ft(t),JSON.stringify({v:1,versionId:e.versionId,nodeId:e.nodeId,compositionId:e.compositionId,startedAt:e.startedAt,reachedAt:e.reachedAt}))}catch(e){v.debug("[workflows] The visitor's position could not be kept",{workflowId:t,error:e})}}function vt(t){w(ft(t))}const wt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,bt=/^[A-Za-z0-9_-]{1,64}$/,yt=new Set(["n","e","f"]),It=new Map([["timeout","t"],["widget_error","e"],["build","b"],["other","o"]]);function kt(t,e,i){return i?`${t}:${e}:${i}`:`${t}:${e}`}class Tt{constructor(t){this.pending=[],this.lastEventOf=new Map,this.flushTimer=null,this.waitingHeights=new Map,this.settledHeights=[],this.reportedSteps=new Set,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,o){if(this.stopped||!this.options.token)return;if(!yt.has(t)||!bt.test(e)||!Number.isInteger(i)||i<1)return;const s="f"===t&&"string"==typeof o?It.get(o):void 0,n=kt(t,e,s);let r=i;for(;r>0;){let i=this.lastEventOf.get(n);(!i||i.c>=50)&&(i=Object.assign({k:t,id:e,c:0},s?{r:s}:{}),this.pending.push(i),this.lastEventOf.set(n,i));const o=Math.min(r,50-i.c);i.c+=o,r-=o}this.pending.length>=100?this.flush():null===this.flushTimer&&(this.flushTimer=setTimeout((()=>this.flush()),2e3))}noteHeight(t,e){if(this.stopped||!this.options.token)return;if(!wt.test(t))return;if(!Number.isFinite(e))return;const i=Math.round(e);if(i<1||i>1e5)return;const o=t.toLowerCase();if(this.reportedSteps.has(o))return;const s=this.waitingHeights.get(o);(null==s?void 0:s.height)!==i&&(!s&&this.waitingHeights.size+this.reportedSteps.size>=10||(s&&clearTimeout(s.timer),this.waitingHeights.set(o,{height:i,timer:setTimeout((()=>this.settleHeight(o)),3e3)})))}flushBeforeLeaving(){if(!this.stopped&&this.options.token)for(this.settleWaitingHeights();this.pending.length>0||this.settledHeights.length>0;){const t=this.takeBatch(),e=this.takeSettledHeights();if(!this.options.isActive())return void this.forgetPending();this.sendWithBeacon(t,e)}}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=kt(e.k,e.id,e.r);this.lastEventOf.get(t)===e&&this.lastEventOf.delete(t)}return t}takeSettledHeights(){return this.settledHeights.splice(0,10)}settleHeight(t){const e=this.waitingHeights.get(t);e&&(this.waitingHeights.delete(t),this.handOver(t,e.height),this.flush())}settleWaitingHeights(){for(const[t,e]of this.waitingHeights)clearTimeout(e.timer),this.handOver(t,e.height);this.waitingHeights.clear()}handOver(t,e){this.reportedSteps.add(t),this.settledHeights.push({compositionId:t,height:e})}forgetPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.pending=[],this.lastEventOf.clear();for(const t of this.waitingHeights.values())clearTimeout(t.timer);this.waitingHeights.clear(),this.settledHeights=[]}flush(){if(null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.stopped||0===this.pending.length&&0===this.settledHeights.length)return;if(!this.options.isActive())return void this.forgetPending();const t=this.takeBatch(),e=this.takeSettledHeights();this.sendWithRequest(t,e),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,e){return JSON.stringify(Object.assign({versionId:this.options.versionId,token:this.options.token,events:t.map((t=>Object.assign(Object.assign({k:t.k,id:t.id},t.c>1?{c:t.c}:{}),t.r?{r:t.r}:{})))},e.length>0?{heights:e}:{}))}sendWithBeacon(t,e){try{const i=this.reportBody(t,e),o="undefined"!=typeof navigator?navigator.sendBeacon:void 0;if("function"==typeof o&&o.call(navigator,this.reportAddress(),new Blob([i],{type:"text/plain"})))return void v.debug("[workflows] Counts handed to the browser to send",{eventCount:t.length,heightCount:e.length})}catch(t){v.debug("[workflows] The browser would not take counts to send as the page closes",{error:t})}this.sendWithRequest(t,e)}sendWithRequest(e,i){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,i)});if(401===t.status)return v.warn("[workflows] The gateway refused the token for counts, so this embed stops reporting",{workflowId:this.options.workflowId}),void this.dispose();v.debug("[workflows] Counts sent",{eventCount:e.length,heightCount:i.length,status:t.status})}catch(t){v.debug("[workflows] Counts could not be sent and were dropped",{eventCount:e.length,heightCount:i.length,error:t})}}))}}const At=/^[a-z0-9]{1,8}(-[a-z0-9]{1,8}){0,4}$/,St=/^[A-Za-z0-9_.:-]{1,128}$/;function Et(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function Ct(t){if("string"!=typeof t||t.length>35)return null;const e=t.toLowerCase();return At.test(e)?e:null}function Ot(){var t,e;try{if("undefined"==typeof navigator)return[];const i=String(null!==(t=navigator.language)&&void 0!==t?t:"").toLowerCase(),o=((null===(e=navigator.languages)||void 0===e?void 0:e.map((t=>String(t).toLowerCase())))||[i]).flatMap((t=>{const e=[t];return t.includes("-")&&e.push(t.split("-")[0]),e}));return[...new Set(o)].filter((t=>""!==t))}catch(t){return v.debug("[workflows] The languages of the browser could not be read",{error:t}),[]}}function Ht(t,e,i){if(!e||0===i.length||!Object.prototype.hasOwnProperty.call(e,t))return t;const o=e[t],{language:s}=function(t,e){const i=Object.keys(e.compositions);for(const e of t)if(i.includes(e))return{language:e,match:"exact"};for(const e of t){const t=e.split("-")[0],o=i.find((e=>e.startsWith(`${t}-`)||e===t));if(void 0!==o)return{language:o,match:"family"}}return{language:e.rootLanguage,match:"root"}}(i,o);return s===o.rootLanguage?t:o.compositions[s]||t}const Nt=/^[A-Za-z0-9_-]{1,64}$/,Mt=/^[A-Za-z0-9_.:-]{1,128}$/;function $t(t){return Nt.test(t)}function Wt(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function Lt(t,e){var i;if(!Wt(t)||!0!==t.success||!Wt(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||!Mt.test(o.versionId))return{kind:"unreadable"};const s=ut(o.graph);if(!s.graph||s.issues.length>0)return v.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};"number"==typeof o.versionNumber&&Number.isInteger(o.versionNumber)&&(n.versionNumber=o.versionNumber),"string"==typeof o.publishedAt&&(n.publishedAt=o.publishedAt),"string"==typeof o.startCompositionId&&Mt.test(o.startCompositionId)&&(n.startCompositionId=o.startCompositionId);const r=function(t){if(!Et(t))return;const e=Object.create(null);let i=0;for(const[o,s]of Object.entries(t)){if(i>=64)break;if(!St.test(o)||!Et(s))continue;const t=Ct(s.rootLanguage);if(null===t||!Et(s.compositions))continue;const n=Object.create(null);let r=0;for(const[t,e]of Object.entries(s.compositions)){if(r>=128)break;const i=Ct(t);null!==i&&"string"==typeof e&&St.test(e)&&(n[i]=e,r+=1)}0!==r&&(e[o]={rootLanguage:t,compositions:n},i+=1)}return 0===i?void 0:e}(o.translations);return r&&(n.translations=r),"string"==typeof o.eventToken&&""!==o.eventToken&&o.eventToken.length<=2048&&(n.eventToken=o.eventToken),{kind:"live",workflow:n}}function Ft(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=Lt(s,i);return"live"===n.kind?{kind:"live",workflow:n.workflow}:n}catch(t){return v.debug("[workflows] A host could not be reached",{workflowId:i,error:t}),{kind:"unreachable"}}finally{clearTimeout(o)}}))}const Rt=new Map;function jt(e,i={}){var o,s;if(!$t(e)||void 0!==i.versionId&&!Mt.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=Rt.get(n);if(r)return r;const a=function(e,i){return t(this,void 0,void 0,(function*(){var t;const o=null!==(t=i.origins)&&void 0!==t?t:I(),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 Ft(`${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 a=n?"not_found":r?"unreadable":"unreachable";return v.debug("[workflows] The workflow is not available",{workflowId:e,reason:a}),{status:"unavailable",reason:a}}))}(e,i);return Rt.set(n,a),a.finally((()=>{Rt.get(n)===a&&Rt.delete(n)})),a}const Pt={clicks:"click",submissions:"submit",plays:"play"},xt=new Set(["__proto__","constructor","prototype"]);function Bt(t){const e=t.detail;return"object"!=typeof e||null===e||Array.isArray(e)?{}:e}function _t(t,e){return("submissions"!==t.metric||"FORM"===e.tagName)&&(("plays"!==t.metric||"VIDEO"===e.tagName||"AUDIO"===e.tagName)&&(null!==t.selector?y(e,t.selector):"clicks"!==t.metric||null!==e.closest('button, a, input[type="button"], input[type="submit"], [role="button"], [onclick], [data-click-track]')))}function zt({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 a=new Set,d=t=>{var s;if(n)return;const r=Bt(t),d=r.table;if("string"!=typeof d||!i.inputTables.includes(d))return;if("string"==typeof r.entryId&&""!==r.entryId){const t=`${d}:${r.entryId}`;if(a.has(t))return;if(a.add(t),a.size>100){const t=a.values().next().value;void 0!==t&&a.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(xt.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(d))&&void 0!==s?s:new Set);v.debug("[workflows] An entry was saved in a watched table",{table:d,valueCount:Object.keys(l).length}),o([{type:"input",table:d,values:l}])};t.addEventListener("widgetic:submitted",d),r.push((()=>t.removeEventListener("widgetic:submitted",d)))}if(i.actionIds.length>0){const s=t=>{if(n)return;const e=Bt(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)&&(v.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 d=[];for(const t of i.actionIds){const i=e(t);i&&(a=i.metric,Object.prototype.hasOwnProperty.call(Pt,a))&&d.push({actionId:t,metric:i.metric,selector:i.selector})}if(d.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 d)Pt[o.metric]===t.type&&_t(o,e)&&i.push({type:"action",actionId:o.actionId});return i},a=t=>{if(n)return;const e=s(t);0!==e.length&&(v.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(d.map((t=>Pt[t.metric])));for(const t of r)n.addEventListener(t,a,!0);e=n,i=()=>{for(const t of r)n.removeEventListener(t,a,!0);e=null,i=()=>{}}};t.addEventListener("widgetic:ready",l),r.push((()=>t.removeEventListener("widgetic:ready",l))),r.push((()=>i())),l()}}var a;return{stop:()=>{if(!n){n=!0;for(const t of r)try{t()}catch(t){v.debug("[workflows] A listener could not be removed",{error:t})}}}}}const Vt=50,Dt=2e3,Ut=150,qt=5,Zt=300,Gt=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 Kt(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 Qt(t,e,i){return null===t||e!==t&&Math.abs(e-t)>=i}const Xt=o,Yt=["width","height","resize","resize-mode","render-mode","use-iframe","theme","mode","colors","sandbox","autoload","adaptive","responsive"],te=["values","context","media-resolver"],ee=["design","content","content-items","contentitems","items"];function ie(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 v.debug("[workflows] The browser could not watch heights",{error:t}),null}}function oe(t){return t.getBoundingClientRect().height}function se(){try{return"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch(t){return!1}}function ne(t){return"number"==typeof t&&Number.isFinite(t)&&t>0}class re{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.firstVisitStage=null,this.firstVisitStageIsReady=!1,this.host=t.host,this.services=t.services,this.prefersReducedMotion=null!==(e=t.prefersReducedMotion)&&void 0!==e?e:se,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}currentCompositionId(){var t,e;return null!==(e=null===(t=this.current)||void 0===t?void 0:t.compositionId)&&void 0!==e?e:null}showFirstStage(t,e=t){if(this.current)return{stage:this.current.element,ready:Promise.resolve({status:"ready"})};this.viewportElement.isConnected||this.host.appendChild(this.viewportElement);const i=this.holdRoomFor(t),o=this.buildStage(t,!0,e);this.current=o,this.firstVisitStage=i||t!==e?null:o;const s=this.waitUntilShown(o,null,(t=>{if("ready"===t.status&&this.firstVisitStage===o&&(this.firstVisitStageIsReady=!0),"ready"===t.status&&!this.destroyed&&this.autoscaleOn&&this.current===o){const t=this.measure(o.element);ne(t)&&this.applyHeight(t,"immediate")}}));return this.viewportElement.appendChild(o.element),this.services.hydrate(o.element),{stage:o.element,ready:s}}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:ie)((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);ne(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,arguments,void 0,(function*(t,e=t){var o,s,n;if(this.destroyed)return{status:"failed",reason:"stopped"};if(this.incoming)return{status:"failed",reason:"busy"};this.enableAutoscale();const r=this.buildStage(t,!1,e);this.incoming=r,this.hideBeside(r.element);const a=this.waitUntilShown(r,null!==(o=this.services.readyTimeoutMilliseconds)&&void 0!==o?o:8e3);this.viewportElement.appendChild(r.element),this.services.hydrate(r.element);const d=yield a;if(this.destroyed)return{status:"failed",reason:"stopped"};if(this.incoming=null,"failed"===d.status)return this.removeStage(r),"timeout"===d.reason&&i(this.host,t,"workflow_step_timeout"),v.debug("[workflows] The next composition could not be shown, so the visitor stays where they are",{compositionId:t,reason:d.reason}),Object.assign({status:"failed",reason:"stopped"===d.reason?"stopped":d.reason},d.code?{code:d.code}:{});const l=this.current;this.revealInPlace(r.element),this.current=r,null===(s=this.heightObserver)||void 0===s||s.observe(r.element);const h=this.measure(r.element);return ne(h)&&this.applyHeight(h,"immediate"),l&&(null===(n=this.heightObserver)||void 0===n||n.unobserve(l.element),this.removeStage(l)),{status:"shown",stage:r.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,i){var o,s,n;const r=document.createElement("widgetic");r.setAttribute("composition-id",t),r.setAttribute(Xt,"1"),r.style.display="block";for(const t of Yt){const e=this.host.getAttribute(t);null!==e&&r.setAttribute(t,e)}this.widthOverride&&r.setAttribute("width",this.widthOverride);for(const t of te){const e=this.host.getAttribute(t);null!==e&&r.setAttribute(t,e)}const a=i===(null!==(o=this.host.getAttribute("composition-id"))&&void 0!==o?o:"").trim();a&&this.copyWhatThePageWroteForTheTagComposition(r);const d={element:r,compositionId:t,standsFor:i,reportedHeight:!1,cancelWait:null,stopListening:()=>{}},l=t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.height;if("number"!=typeof i||!ne(i))return;const o=r.querySelector("iframe");o&&(o.style.height=`${Math.ceil(i)}px`,d.reportedHeight=!0)};r.addEventListener("widgetic:resize",l),d.stopListening=()=>r.removeEventListener("widgetic:resize",l);try{null===(n=(s=this.services).onStageCreated)||void 0===n||n.call(s,r,{compositionId:t,standsFor:i,isFirst:e,carriesPageContent:a})}catch(e){v.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))S(e.name)||t.setAttribute(e.name,e.value);for(const e of ee){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&&te.includes(null!==(e=t.attributeName)&&void 0!==e?e:"")}))&&this.mirrorAttributesToStages()})),this.attributeObserver.observe(this.host,{attributes:!0,attributeFilter:[...te]})}catch(t){this.attributeObserver=null,v.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 te){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 a=e=>{if(!r){r=!0,null!==n&&clearTimeout(n),s.removeEventListener("widgetic:ready",d),s.removeEventListener("widgetic:error",l),s.removeEventListener("load",h,!0),t.cancelWait=null;try{null==i||i(e)}catch(e){v.debug("[workflows] A stage could not be settled",{compositionId:t.compositionId,error:e})}o(e)}},d=()=>a({status:"ready"}),l=t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.code;a(Object.assign({status:"failed",reason:"error"},"string"==typeof i?{code:i}:{}))},h=t=>{t.target instanceof HTMLIFrameElement&&a({status:"ready"})};s.addEventListener("widgetic:ready",d),s.addEventListener("widgetic:error",l),s.addEventListener("load",h,!0),t.cancelWait=()=>a({status:"failed",reason:"stopped"}),null!==e&&(n=setTimeout((()=>a({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){v.debug("[workflows] A listener for a removed stage failed",{compositionId:t.compositionId,error:e})}}noteFrameWithoutHeight(t){this.warnedAboutFrameWithoutHeight||(this.warnedAboutFrameWithoutHeight=!0,v.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:oe)(t)}catch(t){return v.debug("[workflows] The height of a stage could not be read",{error:t}),0}}holdRoomFor(t){const e=k(t);if(null===e)return!1;const i=this.settings();return this.viewportElement.style.minHeight=`${Kt(e,i,this.overlayCap())}px`,!0}settings(){return function(t,e={}){const i=Jt(t,"autoscale-min-height",Vt,Gt),o=Jt(t,"autoscale-max-height",Dt,Gt);return{minHeight:i,maxHeight:Math.max(o,i),debounceDelay:Jt(t,"autoscale-debounce",Ut,5e3),threshold:Jt(t,"autoscale-threshold",qt,Gt),animate:"false"!==t.getAttribute("autoscale-animate")&&!0!==e.prefersReducedMotion,animationDuration:Jt(t,"autoscale-animation-duration",Zt,5e3)}}(this.host,{prefersReducedMotion:this.prefersReducedMotion()})}overlayCap(){return this.host.hasAttribute(s)?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&&ne(e.height)&&this.applyHeight(e.height,"observed")}applyHeight(t,e){this.tellFirstVisitHeight(t);const i=this.settings(),o=Kt(t,i,this.overlayCap());if("immediate"===e)return this.clearHeightTimer(),void this.setHeight(o,i);Qt(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();Qt(this.appliedHeight,t,e.threshold)&&this.setHeight(t,e)}),i.debounceDelay)):o===this.appliedHeight&&this.clearHeightTimer()}tellFirstVisitHeight(t){var e,i;const o=this.current;if(o&&o===this.firstVisitStage&&this.firstVisitStageIsReady&&!this.host.hasAttribute(s)&&(!o.element.querySelector("iframe")||o.reportedHeight))try{null===(i=(e=this.services).onFirstStageHeight)||void 0===i||i.call(e,o.standsFor,Math.ceil(t))}catch(t){v.debug("[workflows] A listener for the height of the first stage failed",{compositionId:o.compositionId,error:t})}}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);T(this.current.compositionId,t,Number.isFinite(e)?e:t)}}clearHeightTimer(){null!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingHeight=null}}const ae=3e4,de=2e3;function le(t,e){return e?"build":"timeout"===t.reason?"timeout":"error"===t.reason?"widget_error":"other"}function he(t,e,i){var o;try{f(t,p(e,i)),null===(o=g(t))||void 0===o||o.sendWorkflowWatch(i)}catch(t){v.debug("[workflows] A widget could not be told what to report",{compositionId:e,error:t})}}function ue(t){try{A(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){v.debug("[workflows] A composition could not be got ready",{compositionId:t,error:e})}}function ce(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 fe{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 r,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.hostIsMarkedMounted=!1,this.copiesThatCannotBeShown=new Set,this.cancelWaitForAnswer=null,this.onPageEvent=t=>{if("ended"===this.mode||"plain"===this.mode)return;const e=a(t.detail);e?"running"!==this.mode||this.stepping?this.pageEvents.add(e):this.hasEnded()||this.react([{type:"pageEvent",name:e.name,values:e.values}]):v.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()},this.visitorLanguages=this.readVisitorLanguages();const n=s.viewport;this.viewport=new re(Object.assign(Object.assign(Object.assign({host:t},n.prefersReducedMotion?{prefersReducedMotion:n.prefersReducedMotion}:{}),o.width?{widthOverride:o.width}:{}),{services:Object.assign(Object.assign(Object.assign(Object.assign({hydrate:o.hydrate},n.createHeightObserver?{createHeightObserver:n.createHeightObserver}:{}),n.measureStageHeight?{measureStageHeight:n.measureStageHeight}:{}),void 0!==n.readyTimeoutMilliseconds?{readyTimeoutMilliseconds:n.readyTimeoutMilliseconds}:{}),{onStageCreated:(t,e)=>this.onStageCreated(t,e.compositionId),onStageRemoved:t=>this.onStageRemoved(t),onFirstStageHeight:(t,e)=>{var i;return null===(i=this.counts)||void 0===i?void 0:i.noteHeight(t,e)}})}))}readVisitorLanguages(){try{const t=this.services.visitorLanguages();return Array.isArray(t)?t.filter((t=>"string"==typeof t)):[]}catch(t){return v.debug("[workflows] The languages of the visitor could not be read",{error:t}),[]}}start(){var t;const e=function(t,e=Date.now()){const i=ft(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:pt(s.versionId)&&pt(s.nodeId)&&pt(s.compositionId)&&gt(s.startedAt)&&gt(s.reachedAt)?s.startedAt>e+864e5?null:e-s.startedAt>2592e6?(vt(t),v.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 v.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(),this.displayBeforeMounting=this.host.style.display,this.run(e,i)}run(e,i){return t(this,void 0,void 0,(function*(){var t;try{const o=this.services.fetchWorkflow(this.workflowId);this.readiedCompositions.add(i),this.services.prefetchComposition(i);const s=yield this.waitForAnswer(o);if(this.hasEnded())return;const n=this.compositionToShow("live"===(null==s?void 0:s.status)?s.workflow:null,i),r=this.showFirstComposition(n,i),[a,d]=yield Promise.all([o,r]);if(this.hasEnded())return;let l=d;if("failed"===l.status&&"stopped"!==l.reason&&n!==i&&(l=yield this.fallBackToTheComposition(n,i),this.hasEnded()))return;let h=e,u=i;if("failed"===l.status){if("stopped"===l.reason)return;if(!e||e.compositionId===this.tagCompositionId)return void this.refuse(l.code);{v.debug("[workflows] The composition a returning visitor was on cannot be shown, so they start again",{compositionId:e.compositionId}),vt(this.workflowId),h=null;const i=yield this.swapToComposition(this.tagCompositionId,"live"===a.status?a.workflow:null);if(this.hasEnded())return;if("shown"!==i.status)return void this.refuse(null!==(t=l.code)&&void 0!==t?t:"failed"===i.status?i.code:void 0);u=this.tagCompositionId}}if("live"!==a.status)return v.debug("[workflows] The workflow is not running, so the tag is a plain embed",{workflowId:this.workflowId,status:a.status}),void(yield this.becomePlain());let c=a.workflow,f=a.origin;if(h&&h.versionId!==c.versionId){const t=yield this.services.fetchWorkflow(this.workflowId,{versionId:h.versionId});if(this.hasEnded())return;"live"===t.status&&t.workflow.versionId===h.versionId?(c=t.workflow,f=t.origin):(v.debug("[workflows] The version a visitor started on cannot be read, so they continue as a new visitor",{versionId:h.versionId}),vt(this.workflowId),h=null)}const p=O(c.graph);let g=h&&this.fitsTheGraph(h,c,p)?h:null;const m=null===g;if(null===g){h&&(v.debug("[workflows] The place a visitor was kept at is not in the workflow, so they continue as a new visitor"),vt(this.workflowId));const t=function(t,e){const i=function(t,e){for(const i of t.nodes)if("composition"===i.type&&i.compositionId===e)return i}(t,e);if(!i)return null;const o=function(t){for(const e of t.nodes)if("composition"===e.type&&!0===e.startsHere)return e}(t);if((null==o?void 0:o.compositionId)===e)return o;if(!o)return i;const s=O(t),n=new Map,r=[o.id];n.set(o.id,0);for(let t=0;t<r.length;t+=1){const e=r[t],i=n.get(e);for(const t of N(s,e))n.has(t.target)||(n.set(t.target,i+1),r.push(t.target))}let a=null,d=1/0;for(const i of t.nodes){if(!M(i)||i.compositionId!==e)continue;const t=n.get(i.id);void 0!==t&&t<d&&(d=t,a=i)}return a||i}(c.graph,this.tagCompositionId);if(!t)return v.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());const e=Date.now();g={versionId:c.versionId,nodeId:t.id,compositionId:this.tagCompositionId,startedAt:e,reachedAt:e}}const w=yield this.showThePlace(g.compositionId,c,u);if(this.hasEnded())return;if("plain"===w)return void(yield this.becomePlain());this.activate(c,f,p,g,m)}catch(t){v.warn("[workflows] The workflow stopped working, so the tag stays as it is",{workflowId:this.workflowId,error:t}),this.becomePlainWithoutWaiting(),this.makeSureTheTagCompositionIsShown()}}))}waitForAnswer(t){const e=this.services.firstCompositionWaitMilliseconds;return new Promise(((i,o)=>{let s=null;const n=t=>{null!==s&&clearTimeout(s),s=null,this.cancelWaitForAnswer=null,i(t)};this.cancelWaitForAnswer=()=>n(null),s=setTimeout((()=>n(null)),Number.isFinite(e)?Math.max(0,e):0),t.then(n,(t=>{null!==s&&clearTimeout(s),s=null,this.cancelWaitForAnswer=null,o(t)}))}))}showFirstComposition(t,e){t!==e&&v.debug("[workflows] A composition is shown in the visitor's language",{compositionId:e,copyId:t});const{ready:i}=this.viewport.showFirstStage(t,e);return this.markHostMounted(),i}markHostMounted(){this.hostIsMarkedMounted||(this.hostIsMarkedMounted=!0,this.options.markMounted(this.host))}makeSureTheTagCompositionIsShown(){if("ended"!==this.mode&&null===this.viewport.currentStage())try{this.viewport.showFirstStage(this.tagCompositionId),this.markHostMounted()}catch(t){v.debug("[workflows] The composition of the tag could not be shown",{error:t})}}compositionToShow(t,e){if(!t)return e;const i=Ht(e,t.translations,this.visitorLanguages);return this.copiesThatCannotBeShown.has(i)?e:i}noteThatTheCopyCannotBeShown(t,e){this.copiesThatCannotBeShown.has(t)||(this.copiesThatCannotBeShown.add(t),v.debug("[workflows] The copy of a composition in the visitor's language cannot be shown, so the composition itself is",{compositionId:e,copyId:t}))}fallBackToTheComposition(e,i){return t(this,void 0,void 0,(function*(){this.noteThatTheCopyCannotBeShown(e,i);const t=yield this.viewport.swapTo(i);return"shown"===t.status?{status:"ready"}:Object.assign({status:"failed",reason:"busy"===t.reason?"error":t.reason},t.code?{code:t.code}:{})}))}swapToComposition(e,i){return t(this,void 0,void 0,(function*(){const t=this.compositionToShow(i,e);t!==e&&v.debug("[workflows] A composition is shown in the visitor's language",{compositionId:e,copyId:t});const o=yield this.viewport.swapTo(t,e);return"shown"===o.status||t===e||"stopped"===o.reason||"busy"===o.reason?o:this.hasEnded()?{status:"failed",reason:"stopped"}:(this.noteThatTheCopyCannotBeShown(t,e),this.viewport.swapTo(e))}))}showThePlace(e,i,o){return t(this,void 0,void 0,(function*(){const t=this.compositionToShow(i,e);if(o===e&&this.viewport.currentCompositionId()===t)return"shown";return"shown"===(yield this.swapToComposition(e,i)).status||o===e?"shown":"plain"}))}fitsTheGraph(t,e,i){if(t.versionId!==e.versionId)return!1;const o=i.nodesById.get(t.nodeId);return M(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)),v.debug("[workflows] The workflow runs",{workflowId:this.workflowId,versionId:t.versionId,isNewVisitor:s}),this.viewport.enableAutoscale();const a=this.viewport.currentStage();a&&this.armStage(a,o.nodeId),this.armSchedules(),this.getNextCompositionsReady(),this.drainPageEvents()}becomePlain(){return t(this,void 0,void 0,(function*(){if(this.mode="plain",this.pageEvents.clear(),this.viewport.currentCompositionId()!==this.tagCompositionId){const t=yield this.viewport.swapTo(this.tagCompositionId);if(this.hasEnded())return;"shown"!==t.status&&v.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),v.debug("[workflows] The composition of the tag cannot be shown",{workflowId:this.workflowId,reason:i})}listenToThePage(){this.host.addEventListener(l,this.onPageEvent),document.addEventListener("visibilitychange",this.onVisibilityChange),this.removeListeners.push((()=>this.host.removeEventListener(l,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,e){this.stages.set(t,{compositionId:e,signals:null,stopWatchingReady:null}),null!==this.pendingStageNodeId&&this.armStage(t,this.pendingStageNodeId)}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 a=r.nodesById.get(e);if(!M(a))return;const d=null!==(i=this.stages.get(t))&&void 0!==i?i:{compositionId:a.compositionId,signals:null,stopWatchingReady:null};null===(o=d.signals)||void 0===o||o.stop(),null===(s=d.stopWatchingReady)||void 0===s||s.call(d),this.stages.set(t,d);const l=it(n.graph,e,{index:r});d.signals=zt({stage:t,watch:l,emit:e=>this.onSignals(t,e)});const u=h(l);if(0===u.tables.length&&0===u.fields.length&&0===u.goals.length)return;const c=()=>this.services.deliverWatch(t,d.compositionId,u);c(),t.addEventListener("widgetic:ready",c),d.stopWatchingReady=()=>t.removeEventListener("widgetic:ready",c)}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=Y(e.graph,{nodeId:o.nodeId},s,{index:i})}catch(t){v.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(!M(s))return;let n;this.stepping=!0,this.cancelRetry(),this.cancelSchedules(),this.pendingStageNodeId=s.id;let r=!1;try{n=yield this.swapToComposition(s.compositionId,this.workflow)}catch(t){v.debug("[workflows] The next composition could not be built",{compositionId:s.compositionId,error:t}),r=!0,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,le(n,r)))}))}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),v.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,s){var n;null===(n=this.counts)||void 0===n||n.count("f",e.id,1,s),v.debug("[workflows] The next composition could not be shown, so the visitor stays where they are",{compositionId:e.compositionId,isRetry:o,reason:s}),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 it(t.graph,i.nodeId,{index:e}).schedules){const t=K(s,i.reachedAt,Date.now());void 0!==t?this.waitFor(o,s,i.nodeId,t):v.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=K(e,o.reachedAt,Date.now());void 0!==n&&(n>0?this.waitFor(t,e,i,n):(v.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)){const i=this.compositionToShow(this.workflow,t);if(!this.readiedCompositions.has(i)){if(e>=5)break;this.readiedCompositions.add(i),e+=1,this.services.prefetchComposition(i)}}})))}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);M(s)?i.includes(s.compositionId)||i.push(s.compositionId):$(s)&&t.push(s.id)}}}}return i}hasEnded(){return"ended"===this.mode||!this.host.isConnected&&(v.debug("[workflows] The tag left the page, so its workflow ends",{workflowId:this.workflowId}),this.stop(),!0)}stop(){var t,e,i,o,s,n;if("ended"!==this.mode){try{null===(t=this.counts)||void 0===t||t.flushBeforeLeaving()}catch(t){v.debug("[workflows] The last counts could not be sent",{error:t})}this.mode="ended",null===(e=this.cancelWaitForAnswer)||void 0===e||e.call(this),this.cancelRetry(),this.cancelSchedules(),null===(i=this.cancelIdleWork)||void 0===i||i.call(this),this.cancelIdleWork=null;for(const t of this.removeListeners.splice(0))t();for(const t of this.stages.values())null===(o=t.signals)||void 0===o||o.stop(),null===(s=t.stopWatchingReady)||void 0===s||s.call(t);this.stages.clear(),this.pageEvents.clear();try{null===(n=this.counts)||void 0===n||n.dispose()}catch(t){v.debug("[workflows] The counts could not be closed",{error:t})}this.viewport.destroy()}}}function pe(t,e){var i,o,s;const r=(null!==(i=t.getAttribute("workflow-id"))&&void 0!==i?i:"").trim(),a=(null!==(o=t.getAttribute("composition-id"))&&void 0!==o?o:"").trim();if(!$t(r)||""===a)return v.debug("[workflows] The tag is not a workflow embed, so it is embedded as it is",{workflowId:r,tagCompositionId:a}),null;const d={fetchWorkflow:jt,createCounts:t=>new Tt(t),deliverWatch:he,prefetchComposition:ue,whenIdle:ce,visitorLanguages:Ot,firstCompositionWaitMilliseconds:2e3,viewport:{}},l=Object.assign(Object.assign(Object.assign({},d),e.services),{viewport:Object.assign(Object.assign({},d.viewport),null===(s=e.services)||void 0===s?void 0:s.viewport)}),h=new fe(t,r,a,e,l);try{h.start()}catch(t){return v.warn("[workflows] The workflow could not start, so the tag is embedded as it is",{workflowId:r,error:t}),h.stop(),null}const u={stop:()=>h.stop()};return n(t,u),u}export{de as FIRST_COMPOSITION_WAIT_MILLISECONDS,ae as RETRY_AFTER_FAILED_STEP_MILLISECONDS,le as failureReasonOf,pe 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.H})))),this.loadChunk("scanner",(()=>import("./chunks/scanner.js").then((function(t){return t.t})))),this.loadChunk("scanner",(()=>import("./chunks/scanner.js").then((function(t){return t.u}))))];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.A})))),this.loadChunk("api",(()=>import("./chunks/api.js").then((function(t){return t.D}))))];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.F})),s=n({debug:this.config.debug,lazyLoading:{enabled:null===(t=this.config.enableLazyLoading)||void 0===t||t,config:{}}});yield s.init(),e.info(`WidgeticBootstrap: Processing ${i.length} widgets through full SDK`)}))}finalizeStats(){this.stats.totalLoadTime=performance.now()-this.initStartTime,this.stats.chunksLoaded=this.loader.getLoadedChunks()}getStats(){return Object.assign({},this.stats)}}let o=null;function d(i){return t(this,void 0,void 0,(function*(){return o?(e.warn("WidgeticBootstrap: Already initialized"),o.getStats()):(o=new r(i),yield o.initialize())}))}function u(){return(null==o?void 0:o.getStats())||null}if("undefined"!=typeof document){const t=()=>{window.__WIDGETIC_SDK_INITIALIZED__||d({debug:"development"===n.NODE_ENV,preloadCritical:!0}).catch((t=>{e.error("WidgeticBootstrap: Auto-initialization failed",t)}))};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):setTimeout(t,0)}"undefined"!=typeof window&&(window.WidgeticBootstrap={init:d,getStats:u,version:"1.0.0"});export{r as BootstrapManager,s as FastWidgetScanner,a as ProgressiveChunkLoader,u as getBootstrapStats,d as initializeWidgeticFast};
1
+ import{_ as t}from"./chunks/vendor.js";import{l as e,e as i,d as n}from"./chunks/core.js";class s{constructor(){this.foundWidgets=[],this.scanStartTime=0}scan(){this.scanStartTime=performance.now();const t=["[data-composition-id]","[data-widget-id]","widgetic-widget","widgetic"],i=[];for(const e of t){const t=document.querySelectorAll(e);for(const e of Array.from(t))this.isValidWidget(e)&&i.push(e)}this.foundWidgets=i;const n=performance.now()-this.scanStartTime;return e.info(`FastScanner: Found ${i.length} widgets in ${n.toFixed(2)}ms`),i}isValidWidget(t){return t.hasAttribute("data-composition-id")||t.hasAttribute("data-widget-id")||t.hasAttribute("composition-id")}getScanTime(){return this.scanStartTime>0?performance.now()-this.scanStartTime:0}}class a{constructor(){this.loadedChunks=new Set,this.loadingPromises=new Map,this.loadStartTime=0,this.loadStartTime=performance.now()}loadCoreChunks(){return t(this,void 0,void 0,(function*(){const t=[this.loadChunk("core",(()=>import("./chunks/core.js").then((function(t){return t.H})))),this.loadChunk("scanner",(()=>import("./chunks/scanner.js").then((function(t){return t.z})))),this.loadChunk("scanner",(()=>import("./chunks/scanner.js").then((function(t){return t.A}))))];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.A})))),this.loadChunk("api",(()=>import("./chunks/api.js").then((function(t){return t.D}))))];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.B}));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.F})),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{k as e,l as n,j as r,G as o,m as f,n as w,o as b,E as T}from"./chunks/api.js";export{B as BatchApiClient,C as CSSDebugger,H as HighLevelAPI,L as LowLevelAPI,M as MidLevelAPI,p as ModuleLoader,q as analyzeWidgetCSS,t as disableCSSDebug,u as enableCSSDebug,g as getBatchClient,a as getModuleLoader,v as monitorWidgetCSS,x as resetBatchClient,y as resetModuleLoader,z as sendWorkflowEvent}from"./chunks/api.js";import{l as R,g as D,C as _,V as O,u as W,e as N,t as V,a as P,T as Q,d as U}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{f as G,W as K}from"./chunks/renderers.js";export{C as CustomElementRenderer,I as IframeRenderer,h as WidgetRenderer,g as getWidgetRenderer,i as resetWidgetRenderer}from"./chunks/renderers.js";export{WidgeticMessenger,getMessenger,resetMessenger}from"./chunks/messaging.js";import{ABTestManager as $}from"./chunks/ABTestManager.js";import{_ as Y}from"./chunks/vendor.js";import{n as J}from"./chunks/scanner.js";export{j as detectBrowserCapabilities,l as determineBestRenderMode,k as isValidWidgetElement,p as parseWidgetConfig}from"./chunks/scanner.js";export{t as toCamel,d as toSnake}from"./chunks/advanced.js";import"./chunks/media.js";import"./chunks/display.js";import"./chunks/performance.js";import"./chunks/security.js";class X{constructor(t){this.deviceDetector=e(),this.privacyCompliance=null,this.eventQueue=[],this.batchTimer=null,this.isOnline=navigator.onLine,this.sessionStartTime=Date.now(),this.lastActivityTime=Date.now(),this.isSessionActive=!1,this.interactionCount=0,this.viewStartTime=Date.now(),this.STORAGE_KEY="widgetic_analytics_queue",this.SESSION_KEY="widgetic_session_id",this.config=Object.assign({batchSize:10,batchTimeout:5e3,maxRetries:3,rateLimitPerMinute:100,enableLocalStorage:!0,enableDeviceTracking:!0,enableInteractionTracking:!0,trackOnlyClicks:!0},t),this.sessionId=this.initializeSession(),this.rateLimitState={eventCounts:new Map,windowStart:Date.now(),windowDurationMs:6e4},this.setupEventListeners(),this.loadQueuedEvents(),R.debug("[AnalyticsTracker] Initialized",{compositionId:this.config.compositionId,sessionId:this.sessionId})}static getInstance(e){if(!X.instance&&e&&(X.instance=new X(e)),!X.instance)throw new Error("AnalyticsTracker must be initialized with config first");return X.instance}static peekInstance(){var e;return null!==(e=X.instance)&&void 0!==e?e:null}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 Y(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 Y(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 D(),n=new _({basePath:this.config.apiEndpoint,accessToken:()=>Y(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${O}`}}),s=new W(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)),X.instance=null,R.debug("[AnalyticsTracker] Destroyed")}}const Z="undefined"!=typeof HTMLElement?HTMLElement:class{};class ee extends Z{constructor(){super(),this.experimentId=null,this.assignment=null,this.widgetInstance=null,this.impressionTracked=!1,this.conversionListeners=new Map,this.renderedVariantId=null,this.isRecording=!1,this.hasStarted=!1,this.currentRunId=0,this.widgetReportsGoals=!1,this.readyWidgetHost=null,this.manager=$.getInstance(),this.widgetManager=n.getInstance(),this.attachShadow({mode:"open"}),this.setupEventListeners()}static get observedAttributes(){return["experiment-id","user-id","session-id","consent"]}connectedCallback(){return Y(this,void 0,void 0,(function*(){this.hasStarted=!0,yield this.start()}))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,i){this.hasStarted&&this.isConnected&&t!==i&&("experiment-id"===e?(this.cleanup(),this.start()):"consent"===e&&this.start())}readConsent(){const e=this.getAttribute("consent");return null===e||"granted"===e?"granted":"denied"===e?"denied":"pending"}start(){return Y(this,void 0,void 0,(function*(){const e=++this.currentRunId,t=()=>e!==this.currentRunId;try{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return N.error("A/B test element missing experiment-id attribute"),void this.renderError("Missing experiment-id attribute");"granted"===this.readConsent()?yield this.startRecorded(t):yield this.startUnrecorded(t)}catch(e){N.error("Failed to initialize A/B test element",{experimentId:this.experimentId,error:e}),this.renderError("Failed to load test")}}))}startRecorded(e){return Y(this,void 0,void 0,(function*(){const t=this.experimentId;this.manager.resumeRecording(t);const i={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0,userAgent:navigator.userAgent,ipAddress:void 0};this.renderedVariantId||this.renderLoading();const n=yield this.manager.getVariantAssignment(t,i);if(!e()){if(!n)return N.warn("No variant assignment received",{experimentId:t}),this.assignment=null,this.isRecording=!1,void this.renderError("Test not available");if(this.assignment=n,this.isRecording=!0,this.impressionTracked=!1,this.setupGoalListeners(),this.renderedVariantId===n.variantId)this.announceVariant();else if(yield this.renderVariant(),e())return;yield this.trackImpression(),this.setupConversionTracking(),this.applyWidgetReadiness(),N.info("A/B test element initialized",{experimentId:t,variantId:n.variantId})}}))}startUnrecorded(e){return Y(this,void 0,void 0,(function*(){const t=this.experimentId,i=this.readConsent();this.isRecording=!1,this.removeConversionListeners(),this.impressionTracked=!1,this.manager.holdRecording(t),"denied"===i&&this.manager.forgetVisitor(t,{userId:this.getAttribute("user-id")||void 0}),this.renderedVariantId||this.renderLoading(),this.setupGoalListeners();const n=yield this.manager.getUnrecordedVariant(t);if(!e()){if(!n)return N.warn("No original version received for the A/B test",{experimentId:t}),this.assignment=null,void this.renderError("Test not available");this.assignment=n,this.renderedVariantId===n.variantId?this.announceVariant():yield this.renderVariant(),N.info("A/B test element shows the original version: analytics is not allowed",{experimentId:t,variantId:n.variantId,consent:i})}}))}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 Y(this,void 0,void 0,(function*(){var e,t;if(!this.assignment||!this.shadowRoot)return;const i=this.assignment,n=this.currentRunId;try{this.removeWidgetInstance(),this.widgetReportsGoals=!1,this.readyWidgetHost=null;const s=document.createElement("div");s.style.cssText="\n width: 100%;\n height: 100%;\n position: relative;\n ",s.setAttribute("data-ab-experiment",this.experimentId||""),s.setAttribute("data-ab-variant",i.variantId);const a=this.createEmbedElement(i.embedCode,i.variantId);if(a){s.appendChild(a);const r={compositionId:i.compositionId,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};if(this.widgetInstance=yield this.widgetManager.registerWidget(`abtest_${this.experimentId}_${i.variantId}_${Date.now()}`,r,a),n!==this.currentRunId)return void this.removeWidgetInstance();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",i.variantId))}this.shadowRoot.innerHTML="",this.shadowRoot.appendChild(s),this.renderedVariantId=i.variantId,a&&this.sendGoalToWidget(a),this.announceVariant()}catch(e){N.error("Failed to render variant",{experimentId:this.experimentId,variantId:i.variantId,error:e}),this.renderError("Failed to render variant")}}))}announceVariant(){this.assignment&&this.dispatchEvent(new CustomEvent("variant-rendered",{detail:{experimentId:this.experimentId,variantId:this.assignment.variantId,compositionId:this.assignment.compositionId,recorded:this.isRecording},bubbles:!0}))}removeWidgetInstance(){if(this.widgetInstance){try{this.widgetManager.unregisterWidget(this.widgetInstance.id)}catch(e){N.warn("Failed to cleanup widget instance",{error:e})}this.widgetInstance=null}}createEmbedElement(e,t){try{const i=new DOMParser,n=i.parseFromString(e,"text/html").body.firstElementChild;if(!n)return N.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",t),s}catch(t){return N.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(),N.debug("Conversion tracking setup complete",{experimentId:this.experimentId,variantId:this.assignment.variantId})}catch(e){N.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?V(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&&!V(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&&!V(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&&this.isRecording)try{const i=this.manager.getPrimaryMetric(this.experimentId);if(!i)return;null===(t=r(e))||void 0===t||t.sendAbGoal({metric:i,goalTarget:this.assignment.goalTarget||null})}catch(e){N.warn("Failed to tell the widget its A/B test goal",{experimentId:this.experimentId,error:e})}}applyWidgetReadiness(){this.experimentId&&this.assignment&&this.isRecording&&this.readyWidgetHost&&(this.manager.setWidgetReportsGoals(this.experimentId,this.widgetReportsGoals),this.assignment.goalTarget&&!this.widgetReportsGoals&&N.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(this.readyWidgetHost))}setupGoalListeners(){if(!this.shadowRoot||this.conversionListeners.has("goal"))return;const e=this.shadowRoot,t=e=>{var t;const i=null===(t=e.detail)||void 0===t?void 0:t.capabilities;this.widgetReportsGoals=Array.isArray(i)&&i.includes(o),this.readyWidgetHost=e.target,this.applyWidgetReadiness()},i=e=>{if(!this.experimentId||!this.assignment||!this.isRecording)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||!this.isRecording)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 Y(this,void 0,void 0,(function*(){var e;if(this.impressionTracked||!this.isRecording||!this.experimentId||!this.assignment)return;const t=this.experimentId,i=this.assignment;try{const n={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0};this.impressionTracked=!0,yield this.manager.trackImpression(t,i.variantId,n),null===(e=X.peekInstance())||void 0===e||e.trackCompositionView({experiment_id:t,variant_id:i.variantId,composition_id:i.compositionId}),N.debug("Impression tracked",{experimentId:t,variantId:i.variantId})}catch(e){N.error("Failed to track impression",{experimentId:t,error:e})}}))}handleConversionEvent(e){var t;this.dispatchEvent(new CustomEvent("conversion",{detail:e,bubbles:!0})),null===(t=X.peekInstance())||void 0===t||t.trackCompositionInteraction({interactionType:"click",elementType:"ab_test_conversion",elementId:e.experimentId,coordinates:{x:0,y:0},duration:0})}onWidgetReady(e){var t,i;N.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;N.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.renderedVariantId=null,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})))}removeConversionListeners(e=!1){this.conversionListeners.forEach(((t,i)=>{("goal"!==i||e)&&(t(),this.conversionListeners.delete(i))}))}cleanup(){this.currentRunId++,this.removeConversionListeners(!0),this.removeWidgetInstance(),this.impressionTracked=!1,this.isRecording=!1,this.renderedVariantId=null,this.widgetReportsGoals=!1,this.readyWidgetHost=null,this.assignment=null}trackConversion(e="custom",t){return this.experimentId&&this.assignment?this.isRecording?this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,t):(N.debug("Conversion not recorded: the visitor has not allowed analytics",{experimentId:this.experimentId}),Promise.resolve()):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",ee))}}ee.register();const te="undefined"!=typeof HTMLElement?HTMLElement:class{};class ie extends te{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.viewIsWaitingForConsent=!1,this.widgetManager=f(),R.debug("[TranslationElement] Created translation element")}static get observedAttributes(){return["consent"]}attributeChangedCallback(e,t,i){"consent"===e&&t!==i&&this.isAnalyticsAllowed()&&this.viewIsWaitingForConsent&&(this.viewIsWaitingForConsent=!1,this.trackTranslationView())}isAnalyticsAllowed(){const e=this.getAttribute("consent");return null===e||"granted"===e}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 Y(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 Y(this,void 0,void 0,(function*(){try{const t=P(),i=new _({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new Q(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 Y(this,void 0,void 0,(function*(){const t=J(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(){if(!this.isAnalyticsAllowed())return this.viewIsWaitingForConsent=!0,void R.debug("[TranslationElement] View not reported: analytics is not allowed yet");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 Y(this,void 0,void 0,(function*(){if(this.isAnalyticsAllowed())try{const t=P(),i=new _({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new Q(i);yield n.submitTranslationAnalyticsEvent({id:this.experimentId,submitTranslationAnalyticsEventRequest:e})}catch(e){R.debug("[TranslationElement] Analytics request failed:",e)}}))}trackFallbackUsage(e,t,i){return Y(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 Y(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",ie),R.info("[TranslationElement] Custom element registered")))}catch(e){R.error("[TranslationElement] Failed to register custom element:",e)}}}ie.register();const ne=w();"undefined"!=typeof window&&"undefined"!=typeof customElements&&(G(),ee.register(),ie.register()),"undefined"!=typeof window&&(window.WidgeticEmbedSDK=ne,window.Widgetic={SDK:ne,getSDK:w,EmbedSDK:T,config:{API_URL:U.API_URL,API_VERSION:U.API_VERSION,CLIENT_URL:U.CLIENT_URL,PRODUCTION_URL:U.PRODUCTION_URL,NODE_ENV:U.NODE_ENV},log:R,WidgeticWidget:K,registerWidgeticWidget:G,cssDebugger:b,enableCSSDebug:()=>b.enableDebugMode(),disableCSSDebug:()=>b.disableDebugMode(),analyzeWidget:e=>b.analyzeWidget(e),ABTestManager:$,ABTestElement:ee,TranslationElement:ie});export{ee as ABTestElement,$ as ABTestManager,T as EmbedSDK,ie as TranslationElement,T as WidgeticEmbedSDK,K as WidgeticWidget,U as config,b as cssDebugger,ne as default,J as generateInstanceId,D as getAuthToken,w as getSDK,R as log,G as registerWidgeticWidget};
1
+ import{k as e,l as n,j as r,G as o,m as l,n as f,o as w,E as b}from"./chunks/api.js";export{B as BatchApiClient,C as CSSDebugger,H as HighLevelAPI,L as LowLevelAPI,M as MidLevelAPI,p as ModuleLoader,q as analyzeWidgetCSS,t as disableCSSDebug,u as enableCSSDebug,g as getBatchClient,a as getModuleLoader,v as monitorWidgetCSS,x as resetBatchClient,y as resetModuleLoader,z as sendWorkflowEvent}from"./chunks/api.js";import{l as T,g as R,C as D,V as _,u as O,e as W,t as N,a as V,T as P,d as Q}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{f as U,W as G}from"./chunks/renderers.js";export{C as CustomElementRenderer,I as IframeRenderer,h as WidgetRenderer,g as getWidgetRenderer,i as resetWidgetRenderer}from"./chunks/renderers.js";export{WidgeticMessenger,getMessenger,resetMessenger}from"./chunks/messaging.js";import{ABTestManager as K}from"./chunks/ABTestManager.js";import{_ as $}from"./chunks/vendor.js";import{v as Y}from"./chunks/scanner.js";export{s as detectBrowserCapabilities,u as determineBestRenderMode,t as isValidWidgetElement,p as parseWidgetConfig}from"./chunks/scanner.js";export{t as toCamel,d as toSnake}from"./chunks/advanced.js";import"./chunks/media.js";import"./chunks/display.js";import"./chunks/performance.js";import"./chunks/security.js";class J{constructor(t){this.deviceDetector=e(),this.privacyCompliance=null,this.eventQueue=[],this.batchTimer=null,this.isOnline=navigator.onLine,this.sessionStartTime=Date.now(),this.lastActivityTime=Date.now(),this.isSessionActive=!1,this.interactionCount=0,this.viewStartTime=Date.now(),this.STORAGE_KEY="widgetic_analytics_queue",this.SESSION_KEY="widgetic_session_id",this.config=Object.assign({batchSize:10,batchTimeout:5e3,maxRetries:3,rateLimitPerMinute:100,enableLocalStorage:!0,enableDeviceTracking:!0,enableInteractionTracking:!0,trackOnlyClicks:!0},t),this.sessionId=this.initializeSession(),this.rateLimitState={eventCounts:new Map,windowStart:Date.now(),windowDurationMs:6e4},this.setupEventListeners(),this.loadQueuedEvents(),T.debug("[AnalyticsTracker] Initialized",{compositionId:this.config.compositionId,sessionId:this.sessionId})}static getInstance(e){if(!J.instance&&e&&(J.instance=new J(e)),!J.instance)throw new Error("AnalyticsTracker must be initialized with config first");return J.instance}static peekInstance(){var e;return null!==(e=J.instance)&&void 0!==e?e:null}initializeSession(){if(this.config.enableLocalStorage){const e=localStorage.getItem(this.SESSION_KEY);if(e)try{const t=JSON.parse(e);if(Date.now()-t.timestamp<18e5)return t.sessionId}catch(e){T.warn("[AnalyticsTracker] Failed to parse stored session",{error:e})}}const e=`sess_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;if(this.config.enableLocalStorage)try{localStorage.setItem(this.SESSION_KEY,JSON.stringify({sessionId:e,timestamp:Date.now()}))}catch(e){T.warn("[AnalyticsTracker] Failed to store session ID",{error:e})}return e}setPrivacyCompliance(e){this.privacyCompliance=e}isTrackingAllowed(){return!this.privacyCompliance||this.privacyCompliance.hasConsent("analytics")}setupEventListeners(){window.addEventListener("online",(()=>{this.isOnline=!0,this.processBatch()})),window.addEventListener("offline",(()=>{this.isOnline=!1})),["mousedown","mousemove","keypress","scroll","touchstart"].forEach((e=>{document.addEventListener(e,(()=>this.updateActivity()),{passive:!0})})),document.addEventListener("visibilitychange",(()=>{document.hidden?this.trackSessionEnd("visibility_hidden"):this.trackSessionStart()})),window.addEventListener("beforeunload",(()=>{this.trackSessionEnd("navigation"),this.flushEvents()}))}updateActivity(){this.lastActivityTime=Date.now(),this.isSessionActive||this.trackSessionStart()}isRateLimited(e){const t=Date.now();t-this.rateLimitState.windowStart>=this.rateLimitState.windowDurationMs&&(this.rateLimitState.eventCounts.clear(),this.rateLimitState.windowStart=t);const i=this.rateLimitState.eventCounts.get(e)||0;return i>=this.config.rateLimitPerMinute?(T.warn("[AnalyticsTracker] Rate limit exceeded",{eventType:e,currentCount:i}),!0):(this.rateLimitState.eventCounts.set(e,i+1),!1)}generateEventId(){return`evt_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}createBaseEvent(e,t={}){const i=this.config.enableDeviceTracking?this.deviceDetector.getDeviceInfo():void 0;return{id:this.generateEventId(),eventType:e,compositionId:this.config.compositionId,timestamp:Date.now(),sessionId:this.sessionId,data:t,deviceInfo:i,referrer:document.referrer||void 0,userAgent:navigator.userAgent,url:window.location.href}}queueEvent(e){this.isTrackingAllowed()?this.isRateLimited(e.eventType)||(this.eventQueue.push(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),this.scheduleBatch(),T.debug("[AnalyticsTracker] Event queued",{eventType:e.eventType,queueSize:this.eventQueue.length})):T.debug("[AnalyticsTracker] Tracking not allowed, skipping event",{eventType:e.eventType})}scheduleBatch(){this.eventQueue.length>=this.config.batchSize?this.processBatch():this.batchTimer||(this.batchTimer=setTimeout((()=>{this.processBatch()}),this.config.batchTimeout))}processBatch(){return $(this,void 0,void 0,(function*(){if(this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),0===this.eventQueue.length||!this.isOnline)return;const e=this.eventQueue.splice(0,this.config.batchSize);try{yield this.sendEventBatch(e),this.config.enableLocalStorage&&this.saveQueueToStorage(),T.debug("[AnalyticsTracker] Batch sent successfully",{batchSize:e.length,remainingQueue:this.eventQueue.length})}catch(t){T.error("[AnalyticsTracker] Failed to send batch",{error:t,batchSize:e.length}),this.eventQueue.unshift(...e),setTimeout((()=>this.processBatch()),5e3)}}))}sendEventBatch(e){return $(this,void 0,void 0,(function*(){if(!this.config.apiEndpoint)return void T.warn("[AnalyticsTracker] No API endpoint configured");const t=e.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer,ip_address:void 0}))),i=yield R(),n=new D({basePath:this.config.apiEndpoint,accessToken:()=>$(this,void 0,void 0,(function*(){return i})),headers:{"X-SDK-Version":`embed-sdk/${_}`}}),s=new O(n);yield s.createAnalyticsEvents({createAnalyticsEventsRequest:{events:t}})}))}saveQueueToStorage(){if(this.config.enableLocalStorage)try{const e={events:this.eventQueue,timestamp:Date.now()};localStorage.setItem(this.STORAGE_KEY,JSON.stringify(e))}catch(e){T.warn("[AnalyticsTracker] Failed to save queue to storage",{error:e})}}loadQueuedEvents(){if(this.config.enableLocalStorage)try{const e=localStorage.getItem(this.STORAGE_KEY);if(e){const t=JSON.parse(e);Date.now()-t.timestamp<864e5?(this.eventQueue=t.events||[],T.debug("[AnalyticsTracker] Loaded queued events from storage",{count:this.eventQueue.length})):localStorage.removeItem(this.STORAGE_KEY)}}catch(e){T.warn("[AnalyticsTracker] Failed to load queued events from storage",{error:e}),localStorage.removeItem(this.STORAGE_KEY)}}flushEvents(){if(0!==this.eventQueue.length&&navigator.sendBeacon&&this.config.apiEndpoint){const e=this.eventQueue.map((e=>({composition_id:e.compositionId,event_type:e.eventType,event_data:e.data,user_id:e.userId,session_id:e.sessionId,user_agent:e.userAgent,referrer:e.referrer})));navigator.sendBeacon(`${this.config.apiEndpoint}/analytics/events/bulk`,JSON.stringify({events:e})),this.eventQueue=[]}}trackCompositionView(e={}){const t=Object.assign({viewportSize:{width:window.innerWidth,height:window.innerHeight},scrollPosition:{x:window.scrollX,y:window.scrollY},loadTime:Date.now()-this.viewStartTime},e),i=this.createBaseEvent("composition_view",t);this.queueEvent(i)}trackCompositionInteraction(e){if(this.config.trackOnlyClicks&&"hover"===e.interactionType)return;this.interactionCount++,this.updateActivity();const t=this.createBaseEvent("composition_interaction",e);this.queueEvent(t)}trackSessionStart(){if(this.isSessionActive)return;this.isSessionActive=!0,this.sessionStartTime=Date.now();const e=this.createBaseEvent("session_start",{sessionDuration:0,pageViews:1,interactions:0});this.queueEvent(e)}trackSessionEnd(e="user_close"){if(!this.isSessionActive)return;this.isSessionActive=!1;const t={sessionDuration:Date.now()-this.sessionStartTime,interactions:this.interactionCount,exitReason:e},i=this.createBaseEvent("session_end",t);this.queueEvent(i)}trackDeviceInfo(){if(!this.config.enableDeviceTracking)return;const e=this.deviceDetector.getDeviceInfo(),t=this.createBaseEvent("device_info",e);this.queueEvent(t)}trackReferrerInfo(){const e={referrer:document.referrer,referrer_domain:document.referrer?new URL(document.referrer).hostname:null,current_url:window.location.href,current_domain:window.location.hostname},t=this.createBaseEvent("referrer_info",e);this.queueEvent(t)}getSessionInfo(){return{sessionId:this.sessionId,isActive:this.isSessionActive,startTime:this.sessionStartTime,lastActivity:this.lastActivityTime,interactionCount:this.interactionCount,duration:Date.now()-this.sessionStartTime}}updateConfig(e){this.config=Object.assign(Object.assign({},this.config),e),T.debug("[AnalyticsTracker] Configuration updated",e)}clearQueue(){this.eventQueue=[],this.config.enableLocalStorage&&localStorage.removeItem(this.STORAGE_KEY),T.debug("[AnalyticsTracker] Event queue cleared")}getStats(){return{queueSize:this.eventQueue.length,sessionInfo:this.getSessionInfo(),rateLimits:Object.fromEntries(this.rateLimitState.eventCounts),isOnline:this.isOnline,trackingAllowed:this.isTrackingAllowed()}}destroy(){this.trackSessionEnd("destroy"),this.flushEvents(),this.batchTimer&&clearTimeout(this.batchTimer),this.config.enableLocalStorage&&(localStorage.removeItem(this.STORAGE_KEY),localStorage.removeItem(this.SESSION_KEY)),J.instance=null,T.debug("[AnalyticsTracker] Destroyed")}}const X="undefined"!=typeof HTMLElement?HTMLElement:class{};class Z extends X{constructor(){super(),this.experimentId=null,this.assignment=null,this.widgetInstance=null,this.impressionTracked=!1,this.conversionListeners=new Map,this.renderedVariantId=null,this.isRecording=!1,this.hasStarted=!1,this.currentRunId=0,this.widgetReportsGoals=!1,this.readyWidgetHost=null,this.manager=K.getInstance(),this.widgetManager=n.getInstance(),this.attachShadow({mode:"open"}),this.setupEventListeners()}static get observedAttributes(){return["experiment-id","user-id","session-id","consent"]}connectedCallback(){return $(this,void 0,void 0,(function*(){this.hasStarted=!0,yield this.start()}))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,i){this.hasStarted&&this.isConnected&&t!==i&&("experiment-id"===e?(this.cleanup(),this.start()):"consent"===e&&this.start())}readConsent(){const e=this.getAttribute("consent");return null===e||"granted"===e?"granted":"denied"===e?"denied":"pending"}start(){return $(this,void 0,void 0,(function*(){const e=++this.currentRunId,t=()=>e!==this.currentRunId;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");"granted"===this.readConsent()?yield this.startRecorded(t):yield this.startUnrecorded(t)}catch(e){W.error("Failed to initialize A/B test element",{experimentId:this.experimentId,error:e}),this.renderError("Failed to load test")}}))}startRecorded(e){return $(this,void 0,void 0,(function*(){const t=this.experimentId;this.manager.resumeRecording(t);const i={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0,userAgent:navigator.userAgent,ipAddress:void 0};this.renderedVariantId||this.renderLoading();const n=yield this.manager.getVariantAssignment(t,i);if(!e()){if(!n)return W.warn("No variant assignment received",{experimentId:t}),this.assignment=null,this.isRecording=!1,void this.renderError("Test not available");if(this.assignment=n,this.isRecording=!0,this.impressionTracked=!1,this.setupGoalListeners(),this.renderedVariantId===n.variantId)this.announceVariant();else if(yield this.renderVariant(),e())return;yield this.trackImpression(),this.setupConversionTracking(),this.applyWidgetReadiness(),W.info("A/B test element initialized",{experimentId:t,variantId:n.variantId})}}))}startUnrecorded(e){return $(this,void 0,void 0,(function*(){const t=this.experimentId,i=this.readConsent();this.isRecording=!1,this.removeConversionListeners(),this.impressionTracked=!1,this.manager.holdRecording(t),"denied"===i&&this.manager.forgetVisitor(t,{userId:this.getAttribute("user-id")||void 0}),this.renderedVariantId||this.renderLoading(),this.setupGoalListeners();const n=yield this.manager.getUnrecordedVariant(t);if(!e()){if(!n)return W.warn("No original version received for the A/B test",{experimentId:t}),this.assignment=null,void this.renderError("Test not available");this.assignment=n,this.renderedVariantId===n.variantId?this.announceVariant():yield this.renderVariant(),W.info("A/B test element shows the original version: analytics is not allowed",{experimentId:t,variantId:n.variantId,consent:i})}}))}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 $(this,void 0,void 0,(function*(){var e,t;if(!this.assignment||!this.shadowRoot)return;const i=this.assignment,n=this.currentRunId;try{this.removeWidgetInstance(),this.widgetReportsGoals=!1,this.readyWidgetHost=null;const s=document.createElement("div");s.style.cssText="\n width: 100%;\n height: 100%;\n position: relative;\n ",s.setAttribute("data-ab-experiment",this.experimentId||""),s.setAttribute("data-ab-variant",i.variantId);const a=this.createEmbedElement(i.embedCode,i.variantId);if(a){s.appendChild(a);const r={compositionId:i.compositionId,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:800,height:600};if(this.widgetInstance=yield this.widgetManager.registerWidget(`abtest_${this.experimentId}_${i.variantId}_${Date.now()}`,r,a),n!==this.currentRunId)return void this.removeWidgetInstance();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",i.variantId))}this.shadowRoot.innerHTML="",this.shadowRoot.appendChild(s),this.renderedVariantId=i.variantId,a&&this.sendGoalToWidget(a),this.announceVariant()}catch(e){W.error("Failed to render variant",{experimentId:this.experimentId,variantId:i.variantId,error:e}),this.renderError("Failed to render variant")}}))}announceVariant(){this.assignment&&this.dispatchEvent(new CustomEvent("variant-rendered",{detail:{experimentId:this.experimentId,variantId:this.assignment.variantId,compositionId:this.assignment.compositionId,recorded:this.isRecording},bubbles:!0}))}removeWidgetInstance(){if(this.widgetInstance){try{this.widgetManager.unregisterWidget(this.widgetInstance.id)}catch(e){W.warn("Failed to cleanup widget instance",{error:e})}this.widgetInstance=null}}createEmbedElement(e,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",t),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?N(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&&!N(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&&!N(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&&this.isRecording)try{const i=this.manager.getPrimaryMetric(this.experimentId);if(!i)return;null===(t=r(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})}}applyWidgetReadiness(){this.experimentId&&this.assignment&&this.isRecording&&this.readyWidgetHost&&(this.manager.setWidgetReportsGoals(this.experimentId,this.widgetReportsGoals),this.assignment.goalTarget&&!this.widgetReportsGoals&&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(this.readyWidgetHost))}setupGoalListeners(){if(!this.shadowRoot||this.conversionListeners.has("goal"))return;const e=this.shadowRoot,t=e=>{var t;const i=null===(t=e.detail)||void 0===t?void 0:t.capabilities;this.widgetReportsGoals=Array.isArray(i)&&i.includes(o),this.readyWidgetHost=e.target,this.applyWidgetReadiness()},i=e=>{if(!this.experimentId||!this.assignment||!this.isRecording)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||!this.isRecording)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 $(this,void 0,void 0,(function*(){var e;if(this.impressionTracked||!this.isRecording||!this.experimentId||!this.assignment)return;const t=this.experimentId,i=this.assignment;try{const n={userId:this.getAttribute("user-id")||void 0,sessionId:this.getAttribute("session-id")||void 0};this.impressionTracked=!0,yield this.manager.trackImpression(t,i.variantId,n),null===(e=J.peekInstance())||void 0===e||e.trackCompositionView({experiment_id:t,variant_id:i.variantId,composition_id:i.compositionId}),W.debug("Impression tracked",{experimentId:t,variantId:i.variantId})}catch(e){W.error("Failed to track impression",{experimentId:t,error:e})}}))}handleConversionEvent(e){var t;this.dispatchEvent(new CustomEvent("conversion",{detail:e,bubbles:!0})),null===(t=J.peekInstance())||void 0===t||t.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.renderedVariantId=null,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})))}removeConversionListeners(e=!1){this.conversionListeners.forEach(((t,i)=>{("goal"!==i||e)&&(t(),this.conversionListeners.delete(i))}))}cleanup(){this.currentRunId++,this.removeConversionListeners(!0),this.removeWidgetInstance(),this.impressionTracked=!1,this.isRecording=!1,this.renderedVariantId=null,this.widgetReportsGoals=!1,this.readyWidgetHost=null,this.assignment=null}trackConversion(e="custom",t){return this.experimentId&&this.assignment?this.isRecording?this.manager.trackConversion(this.experimentId,this.assignment.variantId,e,t):(W.debug("Conversion not recorded: the visitor has not allowed analytics",{experimentId:this.experimentId}),Promise.resolve()):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",Z))}}Z.register();const ee="undefined"!=typeof HTMLElement?HTMLElement:class{};class te extends ee{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.viewIsWaitingForConsent=!1,this.widgetManager=l(),T.debug("[TranslationElement] Created translation element")}static get observedAttributes(){return["consent"]}attributeChangedCallback(e,t,i){"consent"===e&&t!==i&&this.isAnalyticsAllowed()&&this.viewIsWaitingForConsent&&(this.viewIsWaitingForConsent=!1,this.trackTranslationView())}isAnalyticsAllowed(){const e=this.getAttribute("consent");return null===e||"granted"===e}connectedCallback(){if(this.isInitialized)T.debug("[TranslationElement] Already initialized, skipping");else{if(this.experimentId=this.getAttribute("experiment-id"),!this.experimentId)return T.error("[TranslationElement] Missing experiment-id attribute"),void this.displayError("Missing experiment-id attribute");T.debug(`[TranslationElement] Connected with experiment ID: ${this.experimentId}`),this.initializeTranslation()}}disconnectedCallback(){T.debug("[TranslationElement] Disconnected"),this.cleanup()}initializeTranslation(){return $(this,void 0,void 0,(function*(){try{this.isInitialized=!0;const e=this.detectBrowserLanguages();if(T.debug("[TranslationElement] Detected user languages:",e),this.translationData=yield this.fetchTranslationExperiment(this.experimentId),!this.translationData)throw new Error("Failed to fetch translation experiment data");this.selectedLanguage=this.findBestLanguageMatch(e,this.translationData),T.debug("[TranslationElement] Selected language:",this.selectedLanguage);const t=this.getCompositionForLanguage(this.selectedLanguage);if(!t)throw new Error(`No composition found for language: ${this.selectedLanguage}`);yield this.loadWidget(t),T.info("[TranslationElement] Translation experiment loaded successfully",{experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,compositionId:t})}catch(e){T.error("[TranslationElement] Failed to initialize translation:",e),yield this.handleInitializationError(e)}}))}detectBrowserLanguages(){var e;const t=navigator.language.toLowerCase(),i=((null===(e=navigator.languages)||void 0===e?void 0:e.map((e=>e.toLowerCase())))||[t]).flatMap((e=>{const t=[e];return e.includes("-")&&t.push(e.split("-")[0]),t}));return[...new Set(i)]}fetchTranslationExperiment(e){return $(this,void 0,void 0,(function*(){try{const t=V(),i=new D({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new P(i),s=yield n.getTranslationConfig({id:e});return(null==s?void 0:s.data)||null}catch(e){throw T.error("[TranslationElement] Error fetching translation experiment:",e),e}}))}findBestLanguageMatch(e,t){const i=Object.keys(t.languageCompositions||{}),n=t.rootLanguage||"en";T.debug("[TranslationElement] Available languages:",i),T.debug("[TranslationElement] Root language:",n);for(const t of e)if(i.includes(t))return T.debug("[TranslationElement] Found exact match:",t),t;for(const t of e){const e=t.split("-")[0],n=i.find((t=>t.startsWith(e+"-")||t===e));if(n)return T.debug("[TranslationElement] Found base language match:",n),this.trackFallbackUsage(t,n,"language_family").catch((e=>{T.debug("[TranslationElement] Failed to track language family fallback:",e)})),n}T.debug("[TranslationElement] No matches found, falling back to root language:",n);const s=e[0]||"unknown";return this.trackFallbackUsage(s,n,"root_fallback").catch((e=>{T.debug("[TranslationElement] Failed to track root fallback:",e)})),n}getCompositionForLanguage(e){if(!this.translationData)return null;if(e===this.translationData.rootLanguage)return this.translationData.rootCompositionId;return(this.translationData.languageCompositions||{})[e]||this.translationData.rootCompositionId}loadWidget(e){return $(this,void 0,void 0,(function*(){const t=Y(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(){if(!this.isAnalyticsAllowed())return this.viewIsWaitingForConsent=!0,void T.debug("[TranslationElement] View not reported: analytics is not allowed yet");try{const e={experimentId:this.experimentId,selectedLanguage:this.selectedLanguage,userLanguages:this.detectBrowserLanguages(),timestamp:(new Date).toISOString(),userAgent:navigator.userAgent,referrer:document.referrer,url:window.location.href};this.sendAnalytics(e).catch((e=>{T.warn("[TranslationElement] Failed to send analytics:",e)}))}catch(e){T.warn("[TranslationElement] Error in analytics tracking:",e)}}sendAnalytics(e){return $(this,void 0,void 0,(function*(){if(this.isAnalyticsAllowed())try{const t=V(),i=new D({basePath:t,headers:{"X-SDK-Version":"embed-sdk/translations"}}),n=new P(i);yield n.submitTranslationAnalyticsEvent({id:this.experimentId,submitTranslationAnalyticsEventRequest:e})}catch(e){T.debug("[TranslationElement] Analytics request failed:",e)}}))}trackFallbackUsage(e,t,i){return $(this,void 0,void 0,(function*(){try{const n={eventType:"fallback_used",language:t,compositionId:this.getCompositionForLanguage(t)||"",metadata:{requestedLanguage:e,selectedLanguage:t,fallbackType:i,userAgent:navigator.userAgent,timestamp:(new Date).toISOString()},timestamp:(new Date).toISOString()};yield this.sendAnalytics(n),T.debug("[TranslationElement] Fallback usage tracked:",{requested:e,selected:t,fallbackType:i})}catch(e){T.debug("[TranslationElement] Failed to track fallback usage:",e)}}))}handleInitializationError(e){return $(this,void 0,void 0,(function*(){if(this.retryCount<this.maxRetries){this.retryCount++,T.warn(`[TranslationElement] Retrying initialization (${this.retryCount}/${this.maxRetries}):`,e.message),yield new Promise((e=>setTimeout(e,this.retryDelay*this.retryCount)));try{return void(yield this.initializeTranslation())}catch(e){T.error("[TranslationElement] Retry failed:",e)}}this.displayError(`Translation loading failed: ${e.message}`)}))}displayError(e){this.innerHTML=`\n <div style="\n padding: 1rem;\n border: 1px solid #ef4444;\n border-radius: 0.5rem;\n background-color: #fef2f2;\n color: #dc2626;\n font-family: system-ui, -apple-system, sans-serif;\n font-size: 0.875rem;\n margin: 1rem 0;\n ">\n <strong>Translation Error:</strong> ${e}\n </div>\n `}cleanup(){this.widgetInstance&&(this.widgetManager.unregisterWidget(this.widgetInstance.id),this.widgetInstance=null),this.isInitialized=!1,this.retryCount=0}switchLanguage(e){if(!this.translationData)throw new Error("Translation data not loaded");const t=this.getCompositionForLanguage(e);if(!t)throw new Error(`No composition found for language: ${e}`);return this.cleanup(),this.selectedLanguage=e,this.loadWidget(t)}getSelectedLanguage(){return this.selectedLanguage}getAvailableLanguages(){return this.translationData?Object.keys(this.translationData.languageCompositions||{}):[]}static register(){try{"undefined"!=typeof window&&"undefined"!=typeof customElements&&(customElements.get("widgetic-translations")||(customElements.define("widgetic-translations",te),T.info("[TranslationElement] Custom element registered")))}catch(e){T.error("[TranslationElement] Failed to register custom element:",e)}}}te.register();const ie=f();"undefined"!=typeof window&&"undefined"!=typeof customElements&&(U(),Z.register(),te.register()),"undefined"!=typeof window&&(window.WidgeticEmbedSDK=ie,window.Widgetic={SDK:ie,getSDK:f,EmbedSDK:b,config:{API_URL:Q.API_URL,API_VERSION:Q.API_VERSION,CLIENT_URL:Q.CLIENT_URL,PRODUCTION_URL:Q.PRODUCTION_URL,NODE_ENV:Q.NODE_ENV},log:T,WidgeticWidget:G,registerWidgeticWidget:U,cssDebugger:w,enableCSSDebug:()=>w.enableDebugMode(),disableCSSDebug:()=>w.disableDebugMode(),analyzeWidget:e=>w.analyzeWidget(e),ABTestManager:K,ABTestElement:Z,TranslationElement:te});export{Z as ABTestElement,K as ABTestManager,b as EmbedSDK,te as TranslationElement,b as WidgeticEmbedSDK,G as WidgeticWidget,Q as config,w as cssDebugger,ie as default,Y as generateInstanceId,R as getAuthToken,f as getSDK,T as log,U as registerWidgeticWidget};