@widgetic/embed-sdk 2.0.16 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +36 -10
  2. package/dist/browser/chunks/ABTestManager.js +1 -1
  3. package/dist/browser/chunks/api.js +1 -1
  4. package/dist/browser/chunks/core.js +1 -1
  5. package/dist/browser/chunks/renderers.js +1 -1
  6. package/dist/browser/chunks/scanner.js +1 -1
  7. package/dist/browser/chunks/security.js +1 -1
  8. package/dist/browser/chunks/workflows.js +1 -0
  9. package/dist/browser/embed-bootstrap.js +1 -1
  10. package/dist/browser/embed-sdk.js +1 -1
  11. package/dist/esm/chunks/ABTestManager.js +1 -1
  12. package/dist/esm/chunks/api.js +1 -1
  13. package/dist/esm/chunks/core.js +1 -1
  14. package/dist/esm/chunks/renderers.js +1 -1
  15. package/dist/esm/chunks/scanner.js +1 -1
  16. package/dist/esm/chunks/security.js +1 -1
  17. package/dist/esm/chunks/workflows.js +1 -0
  18. package/dist/esm/embed-bootstrap.js +1 -1
  19. package/dist/esm/embed-sdk.js +1 -1
  20. package/dist/esm/types/abTesting/abVisitor.d.ts +2 -0
  21. package/dist/esm/types/core/advanced-security-manager.d.ts +3 -0
  22. package/dist/esm/types/core/autoscale-manager.d.ts +6 -0
  23. package/dist/esm/types/core/widget-manager.d.ts +8 -43
  24. package/dist/esm/types/embed-sdk.d.ts +1 -0
  25. package/dist/esm/types/sdk/embed-sdk.d.ts +1 -0
  26. package/dist/esm/types/utils/declarative-embed-parser.d.ts +5 -0
  27. package/dist/esm/types/utils/host-workflow-watch.d.ts +62 -0
  28. package/dist/esm/types/utils/hydrate-published-host.d.ts +8 -4
  29. package/dist/esm/types/utils/mount-direct-widget.d.ts +12 -0
  30. package/dist/esm/types/utils/public-embed-lookup.d.ts +5 -0
  31. package/dist/esm/types/utils/published-host-bridge.d.ts +10 -0
  32. package/dist/esm/types/utils/workflow-code-loader.d.ts +14 -0
  33. package/dist/esm/types/utils/workflow-code-loader.umd.d.ts +32 -0
  34. package/dist/esm/types/utils/workflow-embed-registry.d.ts +15 -0
  35. package/dist/esm/types/utils/workflow-page-events.d.ts +41 -0
  36. package/dist/esm/types/utils/workflow-shared-contract.d.ts +35 -0
  37. package/dist/esm/types/utils/workflow-shared-services.d.ts +84 -0
  38. package/dist/esm/types/workflows/umd-entry.d.ts +1 -0
  39. package/dist/esm/types/workflows/visitor-position.d.ts +32 -0
  40. package/dist/esm/types/workflows/workflow-autoscale.d.ts +41 -0
  41. package/dist/esm/types/workflows/workflow-counts.d.ts +65 -0
  42. package/dist/esm/types/workflows/workflow-host.d.ts +71 -0
  43. package/dist/esm/types/workflows/workflow-lookup.d.ts +53 -0
  44. package/dist/esm/types/workflows/workflow-signals.d.ts +34 -0
  45. package/dist/esm/types/workflows/workflow-stage.d.ts +154 -0
  46. package/dist/umd/embed-bootstrap.js +1 -1
  47. package/dist/umd/embed-sdk-workflows.js +1 -0
  48. package/dist/umd/embed-sdk.js +1 -1
  49. package/package.json +2 -1
  50. package/dist/esm/types/core/realtime-manager.d.ts +0 -286
package/README.md CHANGED
@@ -77,6 +77,7 @@ export function WidgeticEmbed({ compositionId }) {
77
77
  | `resize` | How the frame follows its place on the page: `fixed` (the default), `fill-width`, `fill-height`, `fixed-width`, `fixed-height`, `fill` or `allow-scale-down`. |
78
78
  | `autoscale` | `on` turns automatic scaling on. Without the attribute, or with `autoscale="false"`, it is off. |
79
79
  | `adaptive` | An adaptive breakpoint in pixels. |
80
+ | `workflow-id` | The id of a published workflow. `composition-id` is then where a new visitor starts (see "Workflows" below). |
80
81
 
81
82
  The tag has more attributes: `embed-target`, and the ones for an overlay, a pop-up and for when a widget shows (`overlay-*`, `popup-*`, `trigger-*`). They are described in the Widgetic Partner integration guide, page 8, "Embed widgets on your pages".
82
83
 
@@ -110,10 +111,27 @@ A widget keeps the language and the colours its author gave it, whatever page it
110
111
 
111
112
  The few words the script draws itself on your page, the accessible names of its close buttons and of the frame, follow the page's own `lang` (`<body lang>` first, then `<html lang>`). Twelve languages are built in, the same twelve that `@widgetic/ui-sdk` ships packs for (French, German, Spanish, Brazilian Portuguese, Dutch, Danish, Swedish, simplified Chinese, Arabic, Hebrew, Persian, Urdu); any other language, and a page that does not say its own, gets English. They are provisional until a native speaker has read them.
112
113
 
113
- The element fires DOM events (bubbling, composed) that match the frame protocol: `widgetic:ready`, `widgetic:error`, `widgetic:submitted`, `widgetic:resize`, `widgetic:data`, `widgetic:interaction`, `widgetic:form-submit`. Lookup failures use `widgetic:error` with `detail.code` in lower case (`not_found`, `domain_not_allowed`, `device_restricted`, …).
114
+ The element fires DOM events (bubbling, composed) that match the frame protocol: `widgetic:ready`, `widgetic:error`, `widgetic:submitted`, `widgetic:resize`, `widgetic:data`, `widgetic:interaction`, `widgetic:form-submit`; a tag with a `workflow-id` also fires `widgetic:workflow-step`. Lookup failures use `widgetic:error` with `detail.code` in lower case (`not_found`, `domain_not_allowed`, `device_restricted`, …).
114
115
 
115
116
  Markers the script writes: `data-widgetic-mounting`, `data-widgetic-mounted`, `data-device-restricted`, `data-widgetic-refused="CODE"`, `data-widgetic-context-invalid`. See `docs/host-contract.md` for the full contract.
116
117
 
118
+ ### Workflows
119
+
120
+ A workflow shows a path of compositions in one place. When a visitor saves an entry, does something in the widget, the page sends an event, or a wait is over, the next composition takes the place of the one on screen, without reloading the page, and the box it sits in follows its height. Draw it in the Widgetic workflows editor, then add its id to the tag you already use:
121
+
122
+ ```html
123
+ <widgetic workflow-id="WORKFLOW_ID" composition-id="FIRST_COMPOSITION_ID" width="800"></widgetic>
124
+ ```
125
+
126
+ - `composition-id` is the composition a **new** visitor starts on, and it has to be one of the workflow's. A workflow that is paused, gone or cannot be read leaves a plain embed of `composition-id`, so the page never shows nothing.
127
+ - Every composition keeps the tag's `width`, `resize`, theme, overlay, and the page's `values`, `context` and `media-resolver`. Inline `design` and `content` overrides written in the tag apply to the composition the tag names only.
128
+ - Autoscale is always on for a workflow tag and reads `autoscale-min-height`, `autoscale-max-height`, `autoscale-debounce`, `autoscale-threshold`, `autoscale-animate` and `autoscale-animation-duration` (defaults 50, 2000, 150, 5, animated, 300). `fixed-height` and `autoscale="false"` are ignored.
129
+ - The tag fires `widgetic:workflow-step` (`{ workflowId, from, to }`) when a visitor moves on. A page tells its workflow that something happened with `sendWorkflowEvent(tag, "name", { value: 1 })`, exported by this package, or by dispatching a `widgetic:workflow-event` (`{ name, values }`) on the tag.
130
+ - Where the visitor is stays in the visitor's own browser (`localStorage`): ids and times, never a value. A visitor finishes the version they started on, for up to 30 days.
131
+ - The workflow code is kept out of what every page downloads. In the code-split builds it is a separate chunk; the single file the CDN serves (`dist/umd/embed-sdk.js`) cannot split, so the code is a second file beside it (`dist/umd/embed-sdk-workflows.js`, about 14 KB gzipped) that the SDK adds to the page when it meets the first tag with a `workflow-id`. Pages without such a tag never download it, and a page where it cannot load keeps a plain embed. A page that serves the SDK itself under another name points to it with `data-workflows-src` on the SDK's script tag.
132
+
133
+ The details, including every trigger and what a widget has to report, are in `__docs/03-features/12-workflows.md`.
134
+
117
135
  ### Telemetry and hosts the script may contact
118
136
 
119
137
  For a typical published embed the script talks to:
@@ -121,6 +139,8 @@ For a typical published embed the script talks to:
121
139
  | Host | When | What is sent |
122
140
  | ------------------------------------------- | ------------------------------------------------------------------ | ---------------------------------------------------------- |
123
141
  | `api.widgetic.com` (or your `data-api-url`) | Composition lookup | Composition id, browser origin (CORS); no API key |
142
+ | `api.widgetic.com` (or your `data-api-url`) | Workflow read, for a tag with `workflow-id` | Workflow id (and version id); no cookies, no headers |
143
+ | `api.widgetic.com` (or your `data-api-url`) | Workflow counts, for a tag with `workflow-id` | Ids of blocks and connections with counts, and a signed token; no visitor, no values, no page address |
124
144
  | `cdn.widgetic.com` | Fallback lookup script | Composition id |
125
145
  | `api.axiom.co` | Optional performance batch (if keys are baked into a custom build) | Aggregated performance summary (no end-user id by default) |
126
146
  | `events.statsigapi.net` | Optional performance batch (if keys are baked into a custom build) | Custom `widget_performance` event with summary payload |
@@ -161,27 +181,33 @@ This package consumes sibling `@widgetic/*` checkouts through a link in `node_mo
161
181
 
162
182
  Here the sibling is `api-sdk`. `npm run i` reinstalls `node_modules` and links that checkout again. `npm run lapisdk` links it again after a fresh `node_modules`.
163
183
 
184
+ The workflows engine, `@widgetic/workflows-engine`, is bundled into the `workflows` chunk (the part only a page with a `<widgetic workflow-id>` tag loads) and comes from npm like any other development dependency. To try a change of the engine that is not published yet, build the sibling checkout (`npm run build` in `../workflows-engine`) and point the package at it (`ln -sfn ../../../workflows-engine node_modules/@widgetic/workflows-engine`); the bundle takes whatever the link holds, so reinstall before a release. `node scripts-sdk/chunk-layout.mjs` prints how the browser build is split into chunks without writing anything, and `tests/unit/scripts/chunk-layout.test.ts` keeps the workflow code and the engine out of the chunks every page loads.
185
+
164
186
  ## Publishing
165
187
 
166
- GitLab CI on `main` publishes this package and then replaces `https://cdn.widgetic.com/sdks/browser/embed-sdk.js`. The npm job is a Trusted Publisher (`NPM_ID_TOKEN`). It does not use a long-lived token.
188
+ A release goes out from a laptop. On a clean `main`:
189
+
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
193
+ npm run publish-to-npm
194
+ ```
167
195
 
168
- 1. Bump `version` in `package.json`.
169
- 2. Commit and push `main`.
170
- 3. The `publish` job runs `npm publish` when that version is not already on npm, then uploads `dist/umd/embed-sdk.js` to the CDN and purges the cached copies.
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.
171
197
 
172
- The CDN upload needs six CI/CD variables on this project, protected, environment scope `cdn`: `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 job purge the cached file.
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.
173
199
 
174
- When the GitLab job fails with `ci_quota_exceeded`, publish from a laptop. That does not use CI minutes. The group's remaining minutes are at [Usage quotas](https://gitlab.com/groups/widgeticai/-/usage_quotas), on the pipelines tab.
200
+ The same release by hand, when the script cannot be used (the dry run first, as above):
175
201
 
176
202
  ```bash
177
203
  npm ci
178
204
  npm run build
179
205
  npm publish --access public
180
- npm run publish:cdn:dry-run -- --env-file .env
181
- npm run publish:cdn -- --purge --allow-dirty --env-file .env
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
182
208
  ```
183
209
 
184
- `npm publish` needs the token in `~/.npmrc`. Do not commit that file. The R2 settings named above have to be in that `.env`, or already in the environment. 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`, uploads the file, 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`. 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 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`.
185
211
 
186
212
  ## License
187
213
 
@@ -1 +1 @@
1
- import{_ as e}from"./vendor.js";import{e as t,C as i,a as n,u as r,b as s}from"./core.js";import{W as o}from"./api.js";import{WidgeticMessenger as a}from"./messaging.js";import{t as d}from"./advanced.js";class c{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}}const l="widgetic_session_id",u=new Map;let v=null;function m(e){var t;try{const t=localStorage.getItem(e);if(null!==t)return t}catch(e){}return null!==(t=u.get(e))&&void 0!==t?t:null}function p(e,i){u.set(e,i);try{localStorage.setItem(e,i)}catch(i){t.debug("localStorage is not available; keeping the A/B test state in memory",{key:e,error:i})}}function g(){const e=m(l);return e||(v||(v=function(){try{if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return`visitor_${crypto.randomUUID()}`}catch(e){}return`visitor_${Math.random().toString(36).slice(2,12)}_${Date.now().toString(36)}`}()),p(l,v),v)}function h(e,t){return function(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return t>>>0}(`${t}:${e}`)%1e4/100}function f(e,i){if(!e||!i)return!1;try{return null!==e.closest(i)}catch(e){return t.warn("The goal target is not a selector this browser understands",{goalTarget:i,error:e}),!1}}class y extends c{constructor(){super(),this.assignments=new Map,this.conversionSetups=new Map,this.trackedConversions=new Set,this.visitors=new Map;const e=new i({basePath:n()});this.abTestingApi=new r(e),this.compositionsApi=new s(e),this.widgetManager=o.getInstance(),this.messenger=new a,this.setupEventListeners()}static getInstance(){return y.instance||(y.instance=new y),y.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(i){return e(this,void 0,void 0,(function*(){var n;try{const r=yield this.abTestingApi.getABTestConfig({id:i});if(!r)return t.warn("A/B test not found",{experimentId:i}),null;const s=(yield Promise.all((r.variants||[]).map((i=>e(this,void 0,void 0,(function*(){try{const e=i.composition_id||i.compositionId||"";return{id:i.id||"",compositionId:e,embedCode:this.generateEmbedCode(e),trafficPercentage:i.traffic_percentage||i.trafficPercentage||0,goalTarget:i.goal_target||i.goalTarget||null}}catch(e){return t.error("Failed to fetch composition for variant",{variantId:i.id,compositionId:i.compositionId,error:e}),null}})))))).filter((e=>null!==e));if(0===s.length)return t.warn("No valid variants found for A/B test",{experimentId:i}),null;const o={experimentId:r.test_id||i,isActive:"running"===r.status,winningVariant:void 0,variants:s,successMetrics:r.success_metrics||["impressions"],primaryMetric:r.primary_metric||(null===(n=r.success_metrics)||void 0===n?void 0:n[0])||"impressions"};return t.info("A/B test config loaded",{experimentId:i,config:o}),o}catch(e){return e&&"object"==typeof e&&"status"in e&&404===e.status?(t.warn("A/B test not found",{experimentId:i}),null):(t.error("Failed to load A/B test config",{experimentId:i,error:e}),null)}}))}resolveVisitor(e){return{userId:(null==e?void 0:e.userId)||void 0,sessionId:(null==e?void 0:e.sessionId)||g()}}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,i){try{const n=m(`ab_test_${e}`);if(!n)return null;const r=JSON.parse(n),s=i.variants.find((e=>e.id===r.variantId));return s?{variantId:s.id,compositionId:s.compositionId,embedCode:s.embedCode,goalTarget:s.goalTarget,recorded:!0===r.recorded}:(t.info("Stored A/B test assignment is no longer a version of the test; assigning again",{experimentId:e}),null)}catch(i){return t.warn("Stored A/B test assignment is unreadable; assigning again",{experimentId:e,error:i}),null}}storeAssignment(e,t){p(`ab_test_${e}`,JSON.stringify(t)),this.assignments.set(e,t)}getVariantAssignment(i,n){return e(this,void 0,void 0,(function*(){try{const e=yield this.getTestConfig(i);if(!e)return null;const t=this.resolveVisitor(n);if(this.visitors.set(i,t),e.winningVariant){const t=e.variants.find((t=>t.id===e.winningVariant));if(t){const e={variantId:t.id,compositionId:t.compositionId,embedCode:t.embedCode,goalTarget:t.goalTarget};return this.storeAssignment(i,e),e}}let r=this.readStoredAssignment(i,e);if(!r){const n=this.selectVariant(i,e.variants,t);if(!n)return null;r={variantId:n.id,compositionId:n.compositionId,embedCode:n.embedCode,goalTarget:n.goalTarget,recorded:!1},this.storeAssignment(i,r)}if(!r.recorded){(yield this.createAssignment(i,r,t))&&(r=Object.assign(Object.assign({},r),{recorded:!0}),this.storeAssignment(i,r))}return this.assignments.set(i,r),yield this.setupConversionTracking(i,e,r),r}catch(e){return t.error("Failed to get variant assignment",{experimentId:i,error:e}),null}}))}setupConversionTracking(i,n,r){return e(this,void 0,void 0,(function*(){var e,s,o;try{const a=[n.primaryMetric],d=yield this.findTrackingTargets(r.compositionId,a),c={experimentId:i,variantId:r.variantId,metrics:a,trackingTargets:d,primaryMetric:n.primaryMetric,goalTarget:null!==(e=r.goalTarget)&&void 0!==e?e:null,widgetReportsGoals:null!==(o=null===(s=this.conversionSetups.get(i))||void 0===s?void 0:s.widgetReportsGoals)&&void 0!==o&&o};this.conversionSetups.set(i,c),t.debug("Conversion tracking setup complete",{experimentId:i,trackedMetrics:a,trackingTargets:d})}catch(e){t.error("Failed to setup conversion tracking",{experimentId:i,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,i){const n=this.conversionSetups.get(e);n&&(n.widgetReportsGoals=i,t.debug("Widget goal reporting capability set",{experimentId:e,widgetReportsGoals:i}))}findTrackingTargets(i,n){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 i of n){const n=t[i]||[];e[i]=n}return e}catch(e){return t.error("Failed to find tracking targets",{compositionId:i,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(i){return e(this,void 0,void 0,(function*(){for(const[e,n]of Array.from(this.conversionSetups.entries()))try{if(!this.widgetManager.getWidget(i))continue;const r=this.messenger.createWidgetController(i);n.metrics.includes("clicks")&&(yield this.setupClickTracking(r,e,n.variantId)),(n.metrics.includes("submissions")||n.metrics.includes("conversions"))&&(yield this.setupFormTracking(r,e,n.variantId)),n.metrics.includes("plays")&&(yield this.setupMediaTracking(r,e,n.variantId)),t.debug("Widget conversion tracking setup",{widgetId:i,experimentId:e})}catch(n){t.error("Failed to setup widget conversion tracking",{widgetId:i,experimentId:e,error:n})}}))}setupClickTracking(t,i,n){return e(this,void 0,void 0,(function*(){t.subscribe("click",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,n,"clicks",{element:t.element,timestamp:t.timestamp})})))),yield t.callFunction("setupEventListener","click",(e=>{var t;this.trackConversion(i,n,"clicks",{target:null===(t=e.target)||void 0===t?void 0:t.tagName,timestamp:Date.now()})}))}))}setupFormTracking(t,i,n){return e(this,void 0,void 0,(function*(){t.subscribe("form-submit",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,n,"submissions",{formData:t.formData,timestamp:t.timestamp})})))),t.subscribe("conversion",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,n,"conversions",{conversionType:t.type,value:t.value,timestamp:t.timestamp})}))))}))}setupMediaTracking(t,i,n){return e(this,void 0,void 0,(function*(){t.subscribe("media-play",(t=>e(this,void 0,void 0,(function*(){yield this.trackConversion(i,n,"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,n]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,n.variantId,e,t.data)}}))}handleMediaEvent(t,i){return e(this,void 0,void 0,(function*(){for(const[e,n]of Array.from(this.conversionSetups.entries()))n.metrics.includes(t)&&(yield this.trackConversion(e,n.variantId,t,i.data))}))}handleFormEvent(t,i){return e(this,void 0,void 0,(function*(){for(const[e,n]of Array.from(this.conversionSetups.entries()))n.metrics.includes(t)&&(yield this.trackConversion(e,n.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(i,n,r,s,o){return e(this,void 0,void 0,(function*(){const e=this.conversionSetups.get(i),a=this.visitorFor(i,o),c=this.conversionKeyFor(i,a);let l=!1;try{if(!e)return void t.warn("Conversion ignored: the test has no assignment in this page yet",{experimentId:i,conversionType:r});if(r!==e.primaryMetric)return void t.debug("Conversion ignored: not the goal this test measures",{experimentId:i,conversionType:r,primaryMetric:e.primaryMetric});const o=null==s?void 0:s.goalTarget;if(e.goalTarget&&e.widgetReportsGoals&&o!==e.goalTarget)return void t.debug("Conversion ignored: not the element this version measures",{experimentId:i,goalTarget:e.goalTarget,reportedGoalTarget:o});if(this.trackedConversions.has(c)||"1"===m(c))return t.debug("Conversion already tracked for this visitor",{experimentId:i,variantId:n,conversionType:r}),void this.trackedConversions.add(c);this.trackedConversions.add(c),l=!0;const u={experimentId:i,variantId:e.variantId||n,userId:a.userId,sessionId:a.sessionId,conversionType:r,goalTarget:e.goalTarget||void 0,timestamp:(new Date).toISOString()},v={event_type:"conversion",data:d(u)};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:v}),p(c,"1"),this.emit("conversion",{experimentId:i,variantId:n,conversionType:r,data:s}),t.info("Conversion tracked",{experimentId:i,variantId:n,conversionType:r,data:s})}catch(e){l&&this.trackedConversions.delete(c),t.error("Failed to track conversion",{experimentId:i,variantId:n,conversionType:r,error:e})}}))}trackImpression(i,n,r){return e(this,void 0,void 0,(function*(){try{const e=this.visitorFor(i,r),s={experimentId:i,variantId:n,userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()},o={event_type:"impression",data:d(s)};yield this.abTestingApi.trackABTestEvent({trackABTestEventRequest:o}),t.debug("Impression tracked",{experimentId:i,variantId:n})}catch(e){t.error("Failed to track impression",{experimentId:i,variantId:n,error:e})}}))}validateGoalTracking(i,n){return e(this,void 0,void 0,(function*(){const e=[],r=[];try{for(const t of i){const i=yield this.validateVariantCapabilities(t,n);e.push(...i)}if(e.length>0){const t=Array.from(new Set(e.map((e=>e.metric))));r.push(`Consider adding trackable elements to your compositions for: ${t.join(", ")}`),t.includes("clicks")&&r.push("Add clickable elements like buttons, links, or interactive components"),t.includes("submissions")&&r.push("Add form elements to track form submissions"),t.includes("plays")&&r.push("Add media elements (audio/video) to track media plays"),t.includes("conversions")&&r.push("Implement custom conversion tracking using widgetic:conversion events")}const s=0===e.length;return t.info("Goal tracking validation completed",{variants:i.length,successMetrics:n,issues:e.length,isValid:s}),{isValid:s,issues:e,recommendations:r}}catch(e){return t.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(i,n){return e(this,void 0,void 0,(function*(){const e=[];try{const r=document.createElement("div");r.style.cssText="position: absolute; top: -9999px; left: -9999px; width: 1px; height: 1px;",document.body.appendChild(r);try{const s={compositionId:i.composition_id,renderMode:"auto",displayMode:"inline",resize:"fill-width",width:1,height:1},o=`validation_${i.composition_id}_${Date.now()}`;if(yield this.widgetManager.registerWidget(o,s,r)){const r=this.messenger.getWidgetController(o);let s=null;if(r)try{s=yield r.callFunction("getCapabilities",[])}catch(e){t.warn("Widget does not expose getCapabilities method",{compositionId:i.composition_id})}for(const t of n){const n=this.checkMetricSupport(i,t,s);n&&e.push(n)}yield this.widgetManager.unregisterWidget(o)}else for(const t of n)e.push({variant:i.name,metric:t,reason:"Widget failed to load for validation"})}finally{document.body.removeChild(r)}}catch(r){t.error("Failed to validate variant capabilities",{variant:i.name,error:r});for(const t of n)e.push({variant:i.name,metric:t,reason:"Validation error occurred"})}return e}))}checkMetricSupport(e,t,i){var n;if(!i)return{variant:e.name,metric:t,reason:"Widget capabilities could not be determined"};switch(t){case"clicks":if(!this.hasClickableCapabilities(i))return{variant:e.name,metric:t,reason:"No clickable elements or interactive capabilities found"};break;case"submissions":if(!i.textCapabilities||!(null===(n=i.textCapabilities.fields)||void 0===n?void 0:n.length))return{variant:e.name,metric:t,reason:"No form fields or text input capabilities found"};break;case"plays":if(!i.mediaCapabilities||!i.mediaCapabilities.supportsPlay)return{variant:e.name,metric:t,reason:"No media playback capabilities found"};break;case"conversions":if("static"===i.type||!i.supportsEvents)return{variant:e.name,metric:t,reason:"Widget may not support custom conversion events"};break;default:return{variant:e.name,metric:t,reason:`Unknown success metric: ${t}`}}return null}hasClickableCapabilities(e){var t,i,n,r;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===(r=null===(n=e.textCapabilities)||void 0===n?void 0:n.fields)||void 0===r?void 0:r.length)return!0;const s=["play","pause","next","previous","goTo","setText","submit","click","interact"];return!!e.exposedFunctions&&s.some((t=>e.exposedFunctions.includes(t)))}selectVariant(e,t,i){return function(e,t,i){if(!e||0===e.length)return null;const n=h(t,i);let r=0;for(const t of e)if(r+=Number(t.trafficPercentage)||0,n<r)return t;return e[e.length-1]}(t,i.userId||i.sessionId,e)}createAssignment(i,n,r){return e(this,void 0,void 0,(function*(){try{const e="undefined"!=typeof navigator?navigator.userAgent:void 0,s={experimentId:i,variantId:n.variantId,userId:r.userId,sessionId:r.sessionId,userAgent:e,deviceType:this.detectDeviceType(e)},o=d(s);return yield this.abTestingApi.createABTestAssignment({createABTestAssignmentRequest:o}),t.debug("Assignment created in backend",{experimentId:i,variantId:n.variantId}),!0}catch(e){return t.error("Failed to create assignment in backend",{experimentId:i,error:e}),!1}}))}generateEmbedCode(e){return`<widgetic-widget composition-id="${e}"></widgetic-widget>`}getSessionId(){return g()}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"}}y.instance=null;var I=Object.freeze({__proto__:null,ABTestManager:y});export{y as A,I as a,f as e};
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};