@widgetic/embed-sdk 2.1.1 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -188,12 +188,12 @@ The workflows engine, `@widgetic/workflows-engine`, is bundled into the `workflo
188
188
  A release goes out from a laptop. On a clean `main`:
189
189
 
190
190
  ```bash
191
- npm whoami # the npm account that publishes
192
- npm run publish:cdn:dry-run -- --skip-build --env-file .env.cdn # changes nothing; proves the CDN settings
191
+ npm whoami # the npm account that publishes
192
+ npm run publish:cdn:settings -- --purge # changes nothing; proves the CDN settings can be read and the bucket answers them
193
193
  npm run publish-to-npm
194
194
  ```
195
195
 
196
- `publish-to-npm` merges what is on `origin/main`, raises the patch version, builds, runs `check:no-secrets`, publishes to npm, replaces `https://cdn.widgetic.com/sdks/browser/embed-sdk-workflows.js` and then `https://cdn.widgetic.com/sdks/browser/embed-sdk.js` and purges the cached copies, commits `chore: publish <version>` with the rebuilt `dist/`, tags `v<version>` and pushes the commit and the tag. `.env.cdn` is git-ignored and holds six settings: `CLOUDFLARE_PUBLIC_ENDPOINT`, `R2_WIDGETS_NAME`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ZONE_ID`. The last two are what let the upload purge the cached file.
196
+ `publish-to-npm` first runs that settings check, before the version is raised (a package that is on npm while the CDN still serves the old file is the half-done release it avoids), then merges what is on `origin/main`, raises the patch version, builds, runs `check:no-secrets`, publishes to npm, replaces `https://cdn.widgetic.com/sdks/browser/embed-sdk-workflows.js` and then `https://cdn.widgetic.com/sdks/browser/embed-sdk.js` and purges the cached copies, commits `chore: publish <version>` with the rebuilt `dist/`, tags `v<version>` and pushes the commit and the tag. The upload reads six settings **from Doppler, every time it runs**: the API gateway's production config (project `api-gateway-service`, config `prd`), with the Doppler CLI you are logged in to (`brew install dopplerhq/cli/doppler`, then `doppler login`). They are the gateway's own names: `CLOUDFLARE_PUBLIC_ENDPOINT`, `R2_WIDGETS_NAME`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ZONE_ID`; the last two are what let the upload purge the cached file. There is no settings file to make or keep in step (the earlier `.env.cdn` and `--env-file` are gone), and a key that is rotated in Doppler is the key the next upload uses. An environment that already holds all of them, the pipeline's `cdn` variables or a shell started with `doppler run`, is used as it is and Doppler is not asked.
197
197
 
198
198
  GitLab CI on `main` is written to do the same (an npm Trusted Publisher, `NPM_ID_TOKEN`, no long-lived token; the six settings as CI/CD variables, protected, environment scope `cdn`), but it does not release this package today. No pipeline on this project has succeeded since 10 October 2026, the latest ones fail within a second with a 0-byte log, and a push to `main` publishes nothing. The usual cause is `ci_quota_exceeded`; the group's remaining minutes are at [Usage quotas](https://gitlab.com/groups/widgeticai/-/usage_quotas), on the pipelines tab. Two things to check before relying on CI again: `package.json` points `@widgetic/api-sdk` at `file:../api-sdk`, a sibling that a CI clone of this project alone does not contain, and the `publish` job uploads the CDN file on every matching push, even when that version is already on npm.
199
199
 
@@ -203,11 +203,11 @@ The same release by hand, when the script cannot be used (the dry run first, as
203
203
  npm ci
204
204
  npm run build
205
205
  npm publish --access public
206
- npm run publish:cdn:dry-run -- --env-file .env.cdn
207
- npm run publish:cdn -- --purge --allow-dirty --env-file .env.cdn # add --allow-create the first time, which creates embed-sdk-workflows.js
206
+ npm run publish:cdn:dry-run
207
+ npm run publish:cdn -- --purge --allow-dirty # add --allow-create the first time, which creates embed-sdk-workflows.js
208
208
  ```
209
209
 
210
- `npm publish` needs the token in `~/.npmrc`. Do not commit that file. The six settings named above have to be in `.env.cdn`, or already in the environment; never commit it either (`.env.*` is git-ignored). The dry run changes nothing. The upload stops when the built `dist/` differs from the committed one, so the laptop command passes `--allow-dirty`. The last command asks you to type `publish` for each of the two files (the workflow file first), uploads them, and purges the cache. Check `npm view @widgetic/embed-sdk version` and the `last-modified` header of `https://cdn.widgetic.com/sdks/browser/embed-sdk.js` and of `https://cdn.widgetic.com/sdks/browser/embed-sdk-workflows.js`. What the upload checks, and how to roll back, is in `__docs/05-advanced/06-publishing-to-cdn.md`.
210
+ `npm publish` needs the token in `~/.npmrc`. Do not commit that file. The six settings named above come from Doppler as described; nothing is kept on disk, and a command line that still passes `--env-file` is refused with a line that says what replaced it. The dry run changes nothing. The upload stops when the built `dist/` differs from the committed one, so the laptop command passes `--allow-dirty`. The last command asks you to type `publish` for each of the two files (the workflow file first), uploads them, and purges the cache. Check `npm view @widgetic/embed-sdk version` and the `last-modified` header of `https://cdn.widgetic.com/sdks/browser/embed-sdk.js` and of `https://cdn.widgetic.com/sdks/browser/embed-sdk-workflows.js`. What the upload checks, and how to roll back, is in `__docs/05-advanced/06-publishing-to-cdn.md`.
211
211
 
212
212
  ## License
213
213
 
@@ -1 +1 @@
1
- import{_ as e}from"./vendor.js";import{C as t,a as i,y as s,b as n,e as r,z as o,r as a,w as d,B as c}from"./core.js";import{k as l}from"./api.js";import{WidgeticMessenger as u}from"./messaging.js";import{t as v}from"./advanced.js";import"./renderers.js";import"./scanner.js";import"./media.js";import"./display.js";import"./performance.js";import"./security.js";class m{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this}off(e,t){const i=this.listeners.get(e);return i&&(i.delete(t),0===i.size&&this.listeners.delete(e)),this}addListener(e,t){return this.on(e,t)}removeListener(e,t){return this.off(e,t)}emit(e,...t){const i=this.listeners.get(e);return!(!i||0===i.size)&&(i.forEach((e=>{try{e(...t)}catch(e){}})),!0)}removeAllListeners(e){return e?this.listeners.delete(e):this.listeners.clear(),this}}class p extends m{constructor(){super(),this.assignments=new Map,this.conversionSetups=new Map,this.trackedConversions=new Set,this.visitors=new Map;const e=new t({basePath:i()});this.abTestingApi=new s(e),this.compositionsApi=new n(e),this.widgetManager=l.getInstance(),this.messenger=new u,this.setupEventListeners()}static getInstance(){return p.instance||(p.instance=new p),p.instance}setupEventListeners(){this.widgetManager.addEventListener("widget_ready",(e=>{this.setupWidgetConversionTracking(e.widgetId)})),this.widgetManager.addEventListener("custom_event",(e=>{this.handleWidgetCustomEvent(e)})),this.widgetManager.addEventListener("media_play",(e=>{this.handleMediaEvent("plays",e)})),this.widgetManager.addEventListener("form_submit",(e=>{this.handleFormEvent("submissions",e)})),this.widgetManager.addEventListener("widget_click",(e=>{this.handleClickEvent(e)}))}getTestConfig(t){return e(this,void 0,void 0,(function*(){var i;try{const s=yield this.abTestingApi.getABTestConfig({id:t});if(!s)return r.warn("A/B test not found",{experimentId:t}),null;const n=(yield Promise.all((s.variants||[]).map((t=>e(this,void 0,void 0,(function*(){try{const e=t.composition_id||t.compositionId||"";return{id:t.id||"",compositionId:e,embedCode:this.generateEmbedCode(e),trafficPercentage:t.traffic_percentage||t.trafficPercentage||0,goalTarget:t.goal_target||t.goalTarget||null}}catch(e){return r.error("Failed to fetch composition for variant",{variantId:t.id,compositionId:t.compositionId,error:e}),null}})))))).filter((e=>null!==e));if(0===n.length)return r.warn("No valid variants found for A/B test",{experimentId:t}),null;const o={experimentId:s.test_id||t,isActive:"running"===s.status,winningVariant:void 0,variants:n,successMetrics:s.success_metrics||["impressions"],primaryMetric:s.primary_metric||(null===(i=s.success_metrics)||void 0===i?void 0:i[0])||"impressions"};return r.info("A/B test config loaded",{experimentId:t,config:o}),o}catch(e){return e&&"object"==typeof e&&"status"in e&&404===e.status?(r.warn("A/B test not found",{experimentId:t}),null):(r.error("Failed to load A/B test config",{experimentId:t,error:e}),null)}}))}resolveVisitor(e){return{userId:(null==e?void 0:e.userId)||void 0,sessionId:(null==e?void 0:e.sessionId)||o()}}visitorFor(e,t){var i;return(null==t?void 0:t.userId)||(null==t?void 0:t.sessionId)?this.resolveVisitor(t):null!==(i=this.visitors.get(e))&&void 0!==i?i:this.resolveVisitor()}readStoredAssignment(e,t){try{const i=a(`ab_test_${e}`);if(!i)return null;const s=JSON.parse(i),n=t.variants.find((e=>e.id===s.variantId));return n?{variantId:n.id,compositionId:n.compositionId,embedCode:n.embedCode,goalTarget:n.goalTarget,recorded:!0===s.recorded}:(r.info("Stored A/B test assignment is no longer a version of the test; assigning again",{experimentId:e}),null)}catch(t){return r.warn("Stored A/B test assignment is unreadable; assigning again",{experimentId:e,error:t}),null}}storeAssignment(e,t){d(`ab_test_${e}`,JSON.stringify(t)),this.assignments.set(e,t)}getVariantAssignment(t,i){return e(this,void 0,void 0,(function*(){try{const e=yield this.getTestConfig(t);if(!e)return null;const s=this.resolveVisitor(i);if(this.visitors.set(t,s),e.winningVariant){const i=e.variants.find((t=>t.id===e.winningVariant));if(i){const e={variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode,goalTarget:i.goalTarget};return this.storeAssignment(t,e),e}}let n=this.readStoredAssignment(t,e);if(!n){const i=this.selectVariant(t,e.variants,s);if(!i)return null;n={variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode,goalTarget:i.goalTarget,recorded:!1},this.storeAssignment(t,n)}if(!n.recorded){(yield this.createAssignment(t,n,s))&&(n=Object.assign(Object.assign({},n),{recorded:!0}),this.storeAssignment(t,n))}return this.assignments.set(t,n),yield this.setupConversionTracking(t,e,n),n}catch(e){return r.error("Failed to get variant assignment",{experimentId:t,error:e}),null}}))}setupConversionTracking(t,i,s){return e(this,void 0,void 0,(function*(){var e,n,o;try{const a=[i.primaryMetric],d=yield this.findTrackingTargets(s.compositionId,a),c={experimentId:t,variantId:s.variantId,metrics:a,trackingTargets:d,primaryMetric:i.primaryMetric,goalTarget:null!==(e=s.goalTarget)&&void 0!==e?e:null,widgetReportsGoals:null!==(o=null===(n=this.conversionSetups.get(t))||void 0===n?void 0:n.widgetReportsGoals)&&void 0!==o&&o};this.conversionSetups.set(t,c),r.debug("Conversion tracking setup complete",{experimentId:t,trackedMetrics:a,trackingTargets:d})}catch(e){r.error("Failed to setup conversion tracking",{experimentId:t,error:e})}}))}getPrimaryMetric(e){var t,i;return null!==(i=null===(t=this.conversionSetups.get(e))||void 0===t?void 0:t.primaryMetric)&&void 0!==i?i:null}setWidgetReportsGoals(e,t){const i=this.conversionSetups.get(e);i&&(i.widgetReportsGoals=t,r.debug("Widget goal reporting capability set",{experimentId:e,widgetReportsGoals:t}))}findTrackingTargets(t,i){return e(this,void 0,void 0,(function*(){try{const e={},t={clicks:["button","a","[data-click-track]","[onclick]"],conversions:["form",'button[type="submit"]',"[data-conversion]"],plays:["video","audio","[data-play]",".play-button"],submissions:["form","[data-form]"],downloads:["a[download]","[data-download]"],signups:["form","[data-signup]",".signup-form"]};for(const s of i){const i=t[s]||[];e[s]=i}return e}catch(e){return r.error("Failed to find tracking targets",{compositionId:t,error:e}),{}}}))}selectorExistsInContent(e,t){const i=e.toLowerCase();if(t.startsWith("[")&&t.endsWith("]")){const e=t.slice(1,-1);return i.includes(e)}if(t.startsWith(".")){const e=t.slice(1);return i.includes(`class="${e}"`)||i.includes(`class='${e}'`)}return i.includes(`<${t}`)}setupWidgetConversionTracking(t){return e(this,void 0,void 0,(function*(){for(const[e,i]of Array.from(this.conversionSetups.entries()))try{if(!this.widgetManager.getWidget(t))continue;const s=this.messenger.createWidgetController(t);i.metrics.includes("clicks")&&(yield this.setupClickTracking(s,e,i.variantId)),(i.metrics.includes("submissions")||i.metrics.includes("conversions"))&&(yield this.setupFormTracking(s,e,i.variantId)),i.metrics.includes("plays")&&(yield this.setupMediaTracking(s,e,i.variantId)),r.debug("Widget conversion tracking setup",{widgetId:t,experimentId:e})}catch(i){r.error("Failed to setup widget conversion tracking",{widgetId:t,experimentId:e,error:i})}}))}setupClickTracking(t,i,s){return e(this,void 0,void 0,(function*(){t.subscribe("click",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"clicks",{element:t.element,timestamp:t.timestamp})})))),yield t.callFunction("setupEventListener","click",(e=>{var t;this.trackConversion(i,s,"clicks",{target:null===(t=e.target)||void 0===t?void 0:t.tagName,timestamp:Date.now()})}))}))}setupFormTracking(t,i,s){return e(this,void 0,void 0,(function*(){t.subscribe("form-submit",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"submissions",{formData:t.formData,timestamp:t.timestamp})})))),t.subscribe("conversion",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"conversions",{conversionType:t.type,value:t.value,timestamp:t.timestamp})}))))}))}setupMediaTracking(t,i,s){return e(this,void 0,void 0,(function*(){t.subscribe("media-play",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"plays",{mediaType:t.mediaType,duration:t.duration,timestamp:t.timestamp})}))))}))}handleWidgetCustomEvent(t){return e(this,void 0,void 0,(function*(){var e;for(const[i,s]of Array.from(this.conversionSetups.entries()))if((null===(e=t.data)||void 0===e?void 0:e.experimentId)===i){const e=t.data.conversionType||"custom";yield this.trackConversion(i,s.variantId,e,t.data)}}))}handleMediaEvent(t,i){return e(this,void 0,void 0,(function*(){for(const[e,s]of Array.from(this.conversionSetups.entries()))s.metrics.includes(t)&&(yield this.trackConversion(e,s.variantId,t,i.data))}))}handleFormEvent(t,i){return e(this,void 0,void 0,(function*(){for(const[e,s]of Array.from(this.conversionSetups.entries()))s.metrics.includes(t)&&(yield this.trackConversion(e,s.variantId,t,i.data))}))}handleClickEvent(t){return e(this,void 0,void 0,(function*(){for(const[e,i]of Array.from(this.conversionSetups.entries()))i.metrics.includes("clicks")&&(yield this.trackConversion(e,i.variantId,"clicks",t.data))}))}conversionKeyFor(e,t){return`ab_converted_${e}_${t.userId||t.sessionId}`}trackConversion(t,i,s,n,o){return e(this,void 0,void 0,(function*(){const e=this.conversionSetups.get(t),c=this.visitorFor(t,o),l=this.conversionKeyFor(t,c);let u=!1;try{if(!e)return void r.warn("Conversion ignored: the test has no assignment in this page yet",{experimentId:t,conversionType:s});if(s!==e.primaryMetric)return void r.debug("Conversion ignored: not the goal this test measures",{experimentId:t,conversionType:s,primaryMetric:e.primaryMetric});const o=null==n?void 0:n.goalTarget;if(e.goalTarget&&e.widgetReportsGoals&&o!==e.goalTarget)return void r.debug("Conversion ignored: not the element this version measures",{experimentId:t,goalTarget:e.goalTarget,reportedGoalTarget:o});if(this.trackedConversions.has(l)||"1"===a(l))return r.debug("Conversion already tracked for this visitor",{experimentId:t,variantId:i,conversionType:s}),void this.trackedConversions.add(l);this.trackedConversions.add(l),u=!0;const m={experimentId:t,variantId:e.variantId||i,userId:c.userId,sessionId:c.sessionId,conversionType:s,goalTarget:e.goalTarget||void 0,timestamp:(new Date).toISOString()},p={event_type:"conversion",data:v(m)};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:p}),d(l,"1"),this.emit("conversion",{experimentId:t,variantId:i,conversionType:s,data:n}),r.info("Conversion tracked",{experimentId:t,variantId:i,conversionType:s,data:n})}catch(e){u&&this.trackedConversions.delete(l),r.error("Failed to track conversion",{experimentId:t,variantId:i,conversionType:s,error:e})}}))}trackImpression(t,i,s){return e(this,void 0,void 0,(function*(){try{const e=this.visitorFor(t,s),n={experimentId:t,variantId:i,userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()},o={event_type:"impression",data:v(n)};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:o}),r.debug("Impression tracked",{experimentId:t,variantId:i})}catch(e){r.error("Failed to track impression",{experimentId:t,variantId:i,error:e})}}))}validateGoalTracking(t,i){return e(this,void 0,void 0,(function*(){const e=[],s=[];try{for(const s of t){const t=yield this.validateVariantCapabilities(s,i);e.push(...t)}if(e.length>0){const t=Array.from(new Set(e.map((e=>e.metric))));s.push(`Consider adding trackable elements to your compositions for: ${t.join(", ")}`),t.includes("clicks")&&s.push("Add clickable elements like buttons, links, or interactive components"),t.includes("submissions")&&s.push("Add form elements to track form submissions"),t.includes("plays")&&s.push("Add media elements (audio/video) to track media plays"),t.includes("conversions")&&s.push("Implement custom conversion tracking using widgetic:conversion events")}const n=0===e.length;return r.info("Goal tracking validation completed",{variants:t.length,successMetrics:i,issues:e.length,isValid:n}),{isValid:n,issues:e,recommendations:s}}catch(e){return r.error("Goal tracking validation failed",{error:e}),{isValid:!1,issues:[{variant:"all",metric:"system",reason:"Validation system error"}],recommendations:["Please try again or contact support"]}}}))}validateVariantCapabilities(t,i){return e(this,void 0,void 0,(function*(){const e=[];try{const s=document.createElement("div");s.style.cssText="position: absolute; top: -9999px; left: -9999px; width: 1px; height: 1px;",document.body.appendChild(s);try{const n={compositionId:t.composition_id,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:1,height:1},o=`validation_${t.composition_id}_${Date.now()}`;if(yield this.widgetManager.registerWidget(o,n,s)){const s=this.messenger.getWidgetController(o);let n=null;if(s)try{n=yield s.callFunction("getCapabilities",[])}catch(e){r.warn("Widget does not expose getCapabilities method",{compositionId:t.composition_id})}for(const s of i){const i=this.checkMetricSupport(t,s,n);i&&e.push(i)}yield this.widgetManager.unregisterWidget(o)}else for(const s of i)e.push({variant:t.name,metric:s,reason:"Widget failed to load for validation"})}finally{document.body.removeChild(s)}}catch(s){r.error("Failed to validate variant capabilities",{variant:t.name,error:s});for(const s of i)e.push({variant:t.name,metric:s,reason:"Validation error occurred"})}return e}))}checkMetricSupport(e,t,i){var s;if(!i)return{variant:e.name,metric:t,reason:"Widget capabilities could not be determined"};switch(t){case"clicks":if(!this.hasClickableCapabilities(i))return{variant:e.name,metric:t,reason:"No clickable elements or interactive capabilities found"};break;case"submissions":if(!i.textCapabilities||!(null===(s=i.textCapabilities.fields)||void 0===s?void 0:s.length))return{variant:e.name,metric:t,reason:"No form fields or text input capabilities found"};break;case"plays":if(!i.mediaCapabilities||!i.mediaCapabilities.supportsPlay)return{variant:e.name,metric:t,reason:"No media playback capabilities found"};break;case"conversions":if("static"===i.type||!i.supportsEvents)return{variant:e.name,metric:t,reason:"Widget may not support custom conversion events"};break;default:return{variant:e.name,metric:t,reason:`Unknown success metric: ${t}`}}return null}hasClickableCapabilities(e){var t,i,s,n;if(["interactive","form","media","gallery"].includes(e.type))return!0;if(null===(t=e.mediaCapabilities)||void 0===t?void 0:t.supportsPlay)return!0;if(null===(i=e.contentCapabilities)||void 0===i?void 0:i.supportsNavigation)return!0;if(null===(n=null===(s=e.textCapabilities)||void 0===s?void 0:s.fields)||void 0===n?void 0:n.length)return!0;const r=["play","pause","next","previous","goTo","setText","submit","click","interact"];return!!e.exposedFunctions&&r.some((t=>e.exposedFunctions.includes(t)))}selectVariant(e,t,i){return c(t,i.userId||i.sessionId,e)}createAssignment(t,i,s){return e(this,void 0,void 0,(function*(){try{const e="undefined"!=typeof navigator?navigator.userAgent:void 0,n={experimentId:t,variantId:i.variantId,userId:s.userId,sessionId:s.sessionId,userAgent:e,deviceType:this.detectDeviceType(e)},o=v(n);return yield this.abTestingApi.createABTestAssignment({createABTestAssignmentRequest:o}),r.debug("Assignment created in backend",{experimentId:t,variantId:i.variantId}),!0}catch(e){return r.error("Failed to create assignment in backend",{experimentId:t,error:e}),!1}}))}generateEmbedCode(e){return`<widgetic-widget composition-id="${e}"></widgetic-widget>`}getSessionId(){return o()}detectDeviceType(e){if(!e)return"desktop";const t=e.toLowerCase();return/tablet|ipad|playbook|silk/.test(t)?"tablet":/mobile|iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/.test(t)?"mobile":"desktop"}}p.instance=null;export{p as ABTestManager};
1
+ import{_ as e}from"./vendor.js";import{C as t,a as i,y as s,b as n,e as r,r as o,z as a,q as d,B as c,w as l,G as u}from"./core.js";import{k as m}from"./api.js";import{WidgeticMessenger as v}from"./messaging.js";import{t as p}from"./advanced.js";import"./renderers.js";import"./scanner.js";import"./media.js";import"./display.js";import"./performance.js";import"./security.js";class g{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this}off(e,t){const i=this.listeners.get(e);return i&&(i.delete(t),0===i.size&&this.listeners.delete(e)),this}addListener(e,t){return this.on(e,t)}removeListener(e,t){return this.off(e,t)}emit(e,...t){const i=this.listeners.get(e);return!(!i||0===i.size)&&(i.forEach((e=>{try{e(...t)}catch(e){}})),!0)}removeAllListeners(e){return e?this.listeners.delete(e):this.listeners.clear(),this}}class h extends g{constructor(){super(),this.assignments=new Map,this.conversionSetups=new Map,this.trackedConversions=new Set,this.visitors=new Map,this.heldExperiments=new Set;const e=new t({basePath:i()});this.abTestingApi=new s(e),this.compositionsApi=new n(e),this.widgetManager=m.getInstance(),this.messenger=new v,this.setupEventListeners()}static getInstance(){return h.instance||(h.instance=new h),h.instance}setupEventListeners(){this.widgetManager.addEventListener("widget_ready",(e=>{this.setupWidgetConversionTracking(e.widgetId)})),this.widgetManager.addEventListener("custom_event",(e=>{this.handleWidgetCustomEvent(e)})),this.widgetManager.addEventListener("media_play",(e=>{this.handleMediaEvent("plays",e)})),this.widgetManager.addEventListener("form_submit",(e=>{this.handleFormEvent("submissions",e)})),this.widgetManager.addEventListener("widget_click",(e=>{this.handleClickEvent(e)}))}getTestConfig(t){return e(this,void 0,void 0,(function*(){var i;try{const s=yield this.abTestingApi.getABTestConfig({id:t});if(!s)return r.warn("A/B test not found",{experimentId:t}),null;const n=(yield Promise.all((s.variants||[]).map((t=>e(this,void 0,void 0,(function*(){try{const e=t.composition_id||t.compositionId||"";return{id:t.id||"",compositionId:e,embedCode:this.generateEmbedCode(e),trafficPercentage:t.traffic_percentage||t.trafficPercentage||0,goalTarget:t.goal_target||t.goalTarget||null}}catch(e){return r.error("Failed to fetch composition for variant",{variantId:t.id,compositionId:t.compositionId,error:e}),null}})))))).filter((e=>null!==e));if(0===n.length)return r.warn("No valid variants found for A/B test",{experimentId:t}),null;const o={experimentId:s.test_id||t,isActive:"running"===s.status,winningVariant:void 0,variants:n,successMetrics:s.success_metrics||["impressions"],primaryMetric:s.primary_metric||(null===(i=s.success_metrics)||void 0===i?void 0:i[0])||"impressions"};return r.info("A/B test config loaded",{experimentId:t,config:o}),o}catch(e){return e&&"object"==typeof e&&"status"in e&&404===e.status?(r.warn("A/B test not found",{experimentId:t}),null):(r.error("Failed to load A/B test config",{experimentId:t,error:e}),null)}}))}holdRecording(e){this.heldExperiments.has(e)||(this.heldExperiments.add(e),r.debug("A/B test recording is held until analytics is allowed",{experimentId:e}))}resumeRecording(e){this.heldExperiments.delete(e)&&r.debug("A/B test recording resumed: analytics is allowed",{experimentId:e})}isRecordingHeld(e){return this.heldExperiments.has(e)}forgetVisitor(e,t){const i=this.visitors.get(e),s=i?i.userId||i.sessionId:(null==t?void 0:t.userId)||o(a);if(d(`ab_test_${e}`),s){const t=this.conversionKeyForVisitorKey(e,s);d(t),this.trackedConversions.delete(t)}this.assignments.delete(e),this.visitors.delete(e),this.conversionSetups.delete(e),0===this.visitors.size&&d(a),r.debug("A/B test visitor forgotten",{experimentId:e})}getUnrecordedVariant(t){return e(this,void 0,void 0,(function*(){try{const e=yield this.getTestConfig(t),i=null==e?void 0:e.variants[0];return e&&i?{variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode,goalTarget:null,recorded:!1}:null}catch(e){return r.error("Failed to get the original version of the A/B test",{experimentId:t,error:e}),null}}))}resolveVisitor(e){return{userId:(null==e?void 0:e.userId)||void 0,sessionId:(null==e?void 0:e.sessionId)||c()}}visitorFor(e,t){var i;return(null==t?void 0:t.userId)||(null==t?void 0:t.sessionId)?this.resolveVisitor(t):null!==(i=this.visitors.get(e))&&void 0!==i?i:this.resolveVisitor()}readStoredAssignment(e,t){try{const i=o(`ab_test_${e}`);if(!i)return null;const s=JSON.parse(i),n=t.variants.find((e=>e.id===s.variantId));return n?{variantId:n.id,compositionId:n.compositionId,embedCode:n.embedCode,goalTarget:n.goalTarget,recorded:!0===s.recorded}:(r.info("Stored A/B test assignment is no longer a version of the test; assigning again",{experimentId:e}),null)}catch(t){return r.warn("Stored A/B test assignment is unreadable; assigning again",{experimentId:e,error:t}),null}}storeAssignment(e,t){l(`ab_test_${e}`,JSON.stringify(t)),this.assignments.set(e,t)}getVariantAssignment(t,i){return e(this,void 0,void 0,(function*(){if(this.isRecordingHeld(t))return r.warn("Variant assignment refused: the visitor has not allowed analytics",{experimentId:t}),null;try{const e=yield this.getTestConfig(t);if(!e)return null;if(this.isRecordingHeld(t))return r.debug("Variant assignment dropped: the visitor said no to analytics meanwhile",{experimentId:t}),null;const s=this.resolveVisitor(i);if(this.visitors.set(t,s),e.winningVariant){const i=e.variants.find((t=>t.id===e.winningVariant));if(i){const e={variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode,goalTarget:i.goalTarget};return this.storeAssignment(t,e),e}}let n=this.readStoredAssignment(t,e);if(!n){const i=this.selectVariant(t,e.variants,s);if(!i)return null;n={variantId:i.id,compositionId:i.compositionId,embedCode:i.embedCode,goalTarget:i.goalTarget,recorded:!1},this.storeAssignment(t,n)}if(!n.recorded){const e=yield this.createAssignment(t,n,s);if(this.isRecordingHeld(t))return r.debug("Assignment not kept: the visitor said no to analytics meanwhile",{experimentId:t}),null;e&&(n=Object.assign(Object.assign({},n),{recorded:!0}),this.storeAssignment(t,n))}return this.assignments.set(t,n),yield this.setupConversionTracking(t,e,n),n}catch(e){return r.error("Failed to get variant assignment",{experimentId:t,error:e}),null}}))}setupConversionTracking(t,i,s){return e(this,void 0,void 0,(function*(){var e,n,o;try{const a=[i.primaryMetric],d=yield this.findTrackingTargets(s.compositionId,a),c={experimentId:t,variantId:s.variantId,metrics:a,trackingTargets:d,primaryMetric:i.primaryMetric,goalTarget:null!==(e=s.goalTarget)&&void 0!==e?e:null,widgetReportsGoals:null!==(o=null===(n=this.conversionSetups.get(t))||void 0===n?void 0:n.widgetReportsGoals)&&void 0!==o&&o};this.conversionSetups.set(t,c),r.debug("Conversion tracking setup complete",{experimentId:t,trackedMetrics:a,trackingTargets:d})}catch(e){r.error("Failed to setup conversion tracking",{experimentId:t,error:e})}}))}getPrimaryMetric(e){var t,i;return null!==(i=null===(t=this.conversionSetups.get(e))||void 0===t?void 0:t.primaryMetric)&&void 0!==i?i:null}setWidgetReportsGoals(e,t){const i=this.conversionSetups.get(e);i&&(i.widgetReportsGoals=t,r.debug("Widget goal reporting capability set",{experimentId:e,widgetReportsGoals:t}))}findTrackingTargets(t,i){return e(this,void 0,void 0,(function*(){try{const e={},t={clicks:["button","a","[data-click-track]","[onclick]"],conversions:["form",'button[type="submit"]',"[data-conversion]"],plays:["video","audio","[data-play]",".play-button"],submissions:["form","[data-form]"],downloads:["a[download]","[data-download]"],signups:["form","[data-signup]",".signup-form"]};for(const s of i){const i=t[s]||[];e[s]=i}return e}catch(e){return r.error("Failed to find tracking targets",{compositionId:t,error:e}),{}}}))}selectorExistsInContent(e,t){const i=e.toLowerCase();if(t.startsWith("[")&&t.endsWith("]")){const e=t.slice(1,-1);return i.includes(e)}if(t.startsWith(".")){const e=t.slice(1);return i.includes(`class="${e}"`)||i.includes(`class='${e}'`)}return i.includes(`<${t}`)}setupWidgetConversionTracking(t){return e(this,void 0,void 0,(function*(){for(const[e,i]of Array.from(this.conversionSetups.entries()))try{if(!this.widgetManager.getWidget(t))continue;const s=this.messenger.createWidgetController(t);i.metrics.includes("clicks")&&(yield this.setupClickTracking(s,e,i.variantId)),(i.metrics.includes("submissions")||i.metrics.includes("conversions"))&&(yield this.setupFormTracking(s,e,i.variantId)),i.metrics.includes("plays")&&(yield this.setupMediaTracking(s,e,i.variantId)),r.debug("Widget conversion tracking setup",{widgetId:t,experimentId:e})}catch(i){r.error("Failed to setup widget conversion tracking",{widgetId:t,experimentId:e,error:i})}}))}setupClickTracking(t,i,s){return e(this,void 0,void 0,(function*(){t.subscribe("click",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"clicks",{element:t.element,timestamp:t.timestamp})})))),yield t.callFunction("setupEventListener","click",(e=>{var t;this.trackConversion(i,s,"clicks",{target:null===(t=e.target)||void 0===t?void 0:t.tagName,timestamp:Date.now()})}))}))}setupFormTracking(t,i,s){return e(this,void 0,void 0,(function*(){t.subscribe("form-submit",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"submissions",{formData:t.formData,timestamp:t.timestamp})})))),t.subscribe("conversion",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"conversions",{conversionType:t.type,value:t.value,timestamp:t.timestamp})}))))}))}setupMediaTracking(t,i,s){return e(this,void 0,void 0,(function*(){t.subscribe("media-play",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,s,"plays",{mediaType:t.mediaType,duration:t.duration,timestamp:t.timestamp})}))))}))}handleWidgetCustomEvent(t){return e(this,void 0,void 0,(function*(){var e;for(const[i,s]of Array.from(this.conversionSetups.entries()))if((null===(e=t.data)||void 0===e?void 0:e.experimentId)===i){const e=t.data.conversionType||"custom";yield this.trackConversion(i,s.variantId,e,t.data)}}))}handleMediaEvent(t,i){return e(this,void 0,void 0,(function*(){for(const[e,s]of Array.from(this.conversionSetups.entries()))s.metrics.includes(t)&&(yield this.trackConversion(e,s.variantId,t,i.data))}))}handleFormEvent(t,i){return e(this,void 0,void 0,(function*(){for(const[e,s]of Array.from(this.conversionSetups.entries()))s.metrics.includes(t)&&(yield this.trackConversion(e,s.variantId,t,i.data))}))}handleClickEvent(t){return e(this,void 0,void 0,(function*(){for(const[e,i]of Array.from(this.conversionSetups.entries()))i.metrics.includes("clicks")&&(yield this.trackConversion(e,i.variantId,"clicks",t.data))}))}conversionKeyFor(e,t){return this.conversionKeyForVisitorKey(e,t.userId||t.sessionId)}conversionKeyForVisitorKey(e,t){return`ab_converted_${e}_${t}`}trackConversion(t,i,s,n,a){return e(this,void 0,void 0,(function*(){if(this.isRecordingHeld(t))return void r.debug("Conversion ignored: the visitor has not allowed analytics",{experimentId:t,conversionType:s});const e=this.conversionSetups.get(t),d=this.visitorFor(t,a),c=this.conversionKeyFor(t,d);let u=!1;try{if(!e)return void r.warn("Conversion ignored: the test has no assignment in this page yet",{experimentId:t,conversionType:s});if(s!==e.primaryMetric)return void r.debug("Conversion ignored: not the goal this test measures",{experimentId:t,conversionType:s,primaryMetric:e.primaryMetric});const a=null==n?void 0:n.goalTarget;if(e.goalTarget&&e.widgetReportsGoals&&a!==e.goalTarget)return void r.debug("Conversion ignored: not the element this version measures",{experimentId:t,goalTarget:e.goalTarget,reportedGoalTarget:a});if(this.trackedConversions.has(c)||"1"===o(c))return r.debug("Conversion already tracked for this visitor",{experimentId:t,variantId:i,conversionType:s}),void this.trackedConversions.add(c);this.trackedConversions.add(c),u=!0;const m={experimentId:t,variantId:e.variantId||i,userId:d.userId,sessionId:d.sessionId,conversionType:s,goalTarget:e.goalTarget||void 0,timestamp:new Date},v={event_type:"conversion",data:p(m)};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:v}),l(c,"1"),this.emit("conversion",{experimentId:t,variantId:i,conversionType:s,data:n}),r.info("Conversion tracked",{experimentId:t,variantId:i,conversionType:s,data:n})}catch(e){u&&this.trackedConversions.delete(c),r.error("Failed to track conversion",{experimentId:t,variantId:i,conversionType:s,error:e})}}))}trackImpression(t,i,s){return e(this,void 0,void 0,(function*(){if(this.isRecordingHeld(t))r.debug("Impression ignored: the visitor has not allowed analytics",{experimentId:t,variantId:i});else try{const e=this.visitorFor(t,s),n={experimentId:t,variantId:i,userId:e.userId,sessionId:e.sessionId,timestamp:new Date},o={event_type:"impression",data:p(n)};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:o}),r.debug("Impression tracked",{experimentId:t,variantId:i})}catch(e){r.error("Failed to track impression",{experimentId:t,variantId:i,error:e})}}))}validateGoalTracking(t,i){return e(this,void 0,void 0,(function*(){const e=[],s=[];try{for(const s of t){const t=yield this.validateVariantCapabilities(s,i);e.push(...t)}if(e.length>0){const t=Array.from(new Set(e.map((e=>e.metric))));s.push(`Consider adding trackable elements to your compositions for: ${t.join(", ")}`),t.includes("clicks")&&s.push("Add clickable elements like buttons, links, or interactive components"),t.includes("submissions")&&s.push("Add form elements to track form submissions"),t.includes("plays")&&s.push("Add media elements (audio/video) to track media plays"),t.includes("conversions")&&s.push("Implement custom conversion tracking using widgetic:conversion events")}const n=0===e.length;return r.info("Goal tracking validation completed",{variants:t.length,successMetrics:i,issues:e.length,isValid:n}),{isValid:n,issues:e,recommendations:s}}catch(e){return r.error("Goal tracking validation failed",{error:e}),{isValid:!1,issues:[{variant:"all",metric:"system",reason:"Validation system error"}],recommendations:["Please try again or contact support"]}}}))}validateVariantCapabilities(t,i){return e(this,void 0,void 0,(function*(){const e=[];try{const s=document.createElement("div");s.style.cssText="position: absolute; top: -9999px; left: -9999px; width: 1px; height: 1px;",document.body.appendChild(s);try{const n={compositionId:t.composition_id,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:1,height:1},o=`validation_${t.composition_id}_${Date.now()}`;if(yield this.widgetManager.registerWidget(o,n,s)){const s=this.messenger.getWidgetController(o);let n=null;if(s)try{n=yield s.callFunction("getCapabilities",[])}catch(e){r.warn("Widget does not expose getCapabilities method",{compositionId:t.composition_id})}for(const s of i){const i=this.checkMetricSupport(t,s,n);i&&e.push(i)}yield this.widgetManager.unregisterWidget(o)}else for(const s of i)e.push({variant:t.name,metric:s,reason:"Widget failed to load for validation"})}finally{document.body.removeChild(s)}}catch(s){r.error("Failed to validate variant capabilities",{variant:t.name,error:s});for(const s of i)e.push({variant:t.name,metric:s,reason:"Validation error occurred"})}return e}))}checkMetricSupport(e,t,i){var s;if(!i)return{variant:e.name,metric:t,reason:"Widget capabilities could not be determined"};switch(t){case"clicks":if(!this.hasClickableCapabilities(i))return{variant:e.name,metric:t,reason:"No clickable elements or interactive capabilities found"};break;case"submissions":if(!i.textCapabilities||!(null===(s=i.textCapabilities.fields)||void 0===s?void 0:s.length))return{variant:e.name,metric:t,reason:"No form fields or text input capabilities found"};break;case"plays":if(!i.mediaCapabilities||!i.mediaCapabilities.supportsPlay)return{variant:e.name,metric:t,reason:"No media playback capabilities found"};break;case"conversions":if("static"===i.type||!i.supportsEvents)return{variant:e.name,metric:t,reason:"Widget may not support custom conversion events"};break;default:return{variant:e.name,metric:t,reason:`Unknown success metric: ${t}`}}return null}hasClickableCapabilities(e){var t,i,s,n;if(["interactive","form","media","gallery"].includes(e.type))return!0;if(null===(t=e.mediaCapabilities)||void 0===t?void 0:t.supportsPlay)return!0;if(null===(i=e.contentCapabilities)||void 0===i?void 0:i.supportsNavigation)return!0;if(null===(n=null===(s=e.textCapabilities)||void 0===s?void 0:s.fields)||void 0===n?void 0:n.length)return!0;const r=["play","pause","next","previous","goTo","setText","submit","click","interact"];return!!e.exposedFunctions&&r.some((t=>e.exposedFunctions.includes(t)))}selectVariant(e,t,i){return u(t,i.userId||i.sessionId,e)}createAssignment(t,i,s){return e(this,void 0,void 0,(function*(){try{const e="undefined"!=typeof navigator?navigator.userAgent:void 0,n={experimentId:t,variantId:i.variantId,userId:s.userId,sessionId:s.sessionId,userAgent:e,deviceType:this.detectDeviceType(e)},o=p(n);return yield this.abTestingApi.createABTestAssignment({createABTestAssignmentRequest:o}),r.debug("Assignment created in backend",{experimentId:t,variantId:i.variantId}),!0}catch(e){return r.error("Failed to create assignment in backend",{experimentId:t,error:e}),!1}}))}generateEmbedCode(e){return`<widgetic-widget composition-id="${e}"></widgetic-widget>`}getSessionId(){return c()}detectDeviceType(e){if(!e)return"desktop";const t=e.toLowerCase();return/tablet|ipad|playbook|silk/.test(t)?"tablet":/mobile|iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/.test(t)?"mobile":"desktop"}}h.instance=null;export{h as ABTestManager};