@xenia-martech/sdk-js 1.0.0-dev.27 → 1.0.0-dev.29

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 (35) hide show
  1. package/CSS_VARIABLES.md +7 -0
  2. package/README.md +50 -1
  3. package/dist/{actions-CkiSdvSa.d.cts → actions-CcBYV--3.d.cts} +177 -1
  4. package/dist/{actions-CkiSdvSa.d.ts → actions-CcBYV--3.d.ts} +177 -1
  5. package/dist/{chunk-UOW3GK4I.cjs → chunk-WYM4CQVG.cjs} +96 -4
  6. package/dist/chunk-WYM4CQVG.cjs.map +1 -0
  7. package/dist/{chunk-7D2HJMW6.js → chunk-XXNDHYAS.js} +96 -4
  8. package/dist/chunk-XXNDHYAS.js.map +1 -0
  9. package/dist/client/index.cjs +543 -27
  10. package/dist/client/index.cjs.map +1 -1
  11. package/dist/client/index.d.cts +112 -3
  12. package/dist/client/index.d.ts +112 -3
  13. package/dist/client/index.js +540 -28
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/react/index.cjs +539 -27
  16. package/dist/client/react/index.cjs.map +1 -1
  17. package/dist/client/react/index.d.cts +2 -2
  18. package/dist/client/react/index.d.ts +2 -2
  19. package/dist/client/react/index.js +539 -27
  20. package/dist/client/react/index.js.map +1 -1
  21. package/dist/{cookie-names-C3LKDhsg.d.cts → cookie-names-B3b0XNc2.d.cts} +153 -1
  22. package/dist/{cookie-names-C3LKDhsg.d.ts → cookie-names-B3b0XNc2.d.ts} +153 -1
  23. package/dist/index.cjs +20 -20
  24. package/dist/index.d.cts +2 -2
  25. package/dist/index.d.ts +2 -2
  26. package/dist/index.js +1 -1
  27. package/dist/server/index.cjs +15 -15
  28. package/dist/server/index.d.cts +2 -2
  29. package/dist/server/index.d.ts +2 -2
  30. package/dist/server/index.js +2 -2
  31. package/dist/xenia-sdk.iife.js +37 -3
  32. package/dist/xenia-sdk.iife.js.map +1 -1
  33. package/package.json +1 -1
  34. package/dist/chunk-7D2HJMW6.js.map +0 -1
  35. package/dist/chunk-UOW3GK4I.cjs.map +0 -1
@@ -13,6 +13,7 @@ var MESSAGE_POSITIONS = /* @__PURE__ */ new Set([
13
13
  "top",
14
14
  "bottom"
15
15
  ]);
16
+ var WIDGET_TYPES = /* @__PURE__ */ new Set(["standard", "spin-wheel"]);
16
17
  var ALL_TYPES = /* @__PURE__ */ new Set([
17
18
  "swap",
18
19
  "hide",
@@ -59,15 +60,67 @@ function toAction(raw) {
59
60
  message: asString(raw.message),
60
61
  imageUrl: asString(raw.imageUrl),
61
62
  html: asString(raw.html),
62
- cta: cta && cta.label ? cta : void 0,
63
+ // A link-only CTA (empty label, e.g. a spin-wheel's data-xenia-wheel-cta —
64
+ // label is meaningless there, the winHtml/lossHtml design supplies its own button text)
65
+ // must still parse through — gating on `cta.label` alone silently dropped it.
66
+ cta: cta && (cta.label || cta.url) ? cta : void 0,
63
67
  dismissAfterMs: asNumber(raw.dismissAfterMs),
64
- position: asMessagePosition(raw.position)
68
+ position: asMessagePosition(raw.position),
69
+ widgetType: asWidgetType(raw.widgetType),
70
+ segments: asSegments(raw.segments),
71
+ formSubmit: asFormSubmit(raw.formSubmit),
72
+ style: asWidgetStyle(raw.style),
73
+ spinnerHtml: asString(raw.spinnerHtml),
74
+ winHtml: asString(raw.winHtml),
75
+ lossHtml: asString(raw.lossHtml)
65
76
  };
66
77
  }
67
78
  function asMessagePosition(v) {
68
79
  const s = asString(v);
69
80
  return s && MESSAGE_POSITIONS.has(s) ? s : void 0;
70
81
  }
82
+ function asWidgetType(v) {
83
+ const s = asString(v);
84
+ return s && WIDGET_TYPES.has(s) ? s : void 0;
85
+ }
86
+ function asSegments(v) {
87
+ if (!Array.isArray(v)) return void 0;
88
+ const segments = [];
89
+ for (const entry of v) {
90
+ if (!isObject(entry)) continue;
91
+ const id = asString(entry.id);
92
+ const label = asString(entry.label);
93
+ if (!id || !label) continue;
94
+ segments.push({
95
+ id,
96
+ label,
97
+ colorHex: asString(entry.colorHex),
98
+ isLoss: entry.isLoss === true
99
+ });
100
+ }
101
+ return segments.length ? segments : void 0;
102
+ }
103
+ function asFormSubmit(v) {
104
+ if (!isObject(v)) return void 0;
105
+ const mode = asString(v.mode);
106
+ if (!mode) return void 0;
107
+ return {
108
+ requiresResolve: v.requiresResolve === true,
109
+ mode,
110
+ flowRef: asString(v.flowRef),
111
+ bindingRef: asString(v.bindingRef),
112
+ successDisplayMs: asNumber(v.successDisplayMs)
113
+ };
114
+ }
115
+ function asWidgetStyle(v) {
116
+ if (!isObject(v)) return void 0;
117
+ const style = {
118
+ hideCloseButton: v.hideCloseButton === true,
119
+ hideOverlay: v.hideOverlay === true
120
+ };
121
+ const hasAny = style.hideCloseButton || style.hideOverlay;
122
+ return hasAny ? style : void 0;
123
+ }
71
124
  function parseActions(body) {
72
125
  let list;
73
126
  if (Array.isArray(body)) {
@@ -250,6 +303,12 @@ var TokenProvider = class {
250
303
  };
251
304
 
252
305
  // src/core/api.ts
306
+ function isJsonObject(v) {
307
+ return typeof v === "object" && v !== null && !Array.isArray(v);
308
+ }
309
+ function asWidgetPrize(v) {
310
+ return v !== void 0 && isJsonObject(v) ? v : void 0;
311
+ }
253
312
  function compact(obj) {
254
313
  const out = {};
255
314
  for (const [k, v] of Object.entries(obj)) {
@@ -319,6 +378,39 @@ var XeniaApi = class {
319
378
  receivedAt: Date.now()
320
379
  };
321
380
  }
381
+ /**
382
+ * Widget form submission — `POST /widget-submissions?ref={bindingRef}`. Used whenever the
383
+ * action's `formSubmit.requiresResolve` is true (spin-wheel, which must have a
384
+ * server-resolved outcome before anything renders) or `mode === "endpoint"` — the common
385
+ * plain-popup case (`mode === "journey" && !requiresResolve`) bypasses this entirely and calls
386
+ * {@link webhook} against `flowRef` instead (see `XeniaClient.submitWidgetForm`'s endpoint
387
+ * selection).
388
+ *
389
+ * Not retried (`noRetry: true`), styled like {@link webhook} — a retried POST must never
390
+ * double-fire a journey or double-resolve a prize server-side.
391
+ */
392
+ async submitWidget(ref, body) {
393
+ const { response, data: rawBody } = await this.http.request({
394
+ method: "POST",
395
+ path: "/widget-submissions",
396
+ query: { ref },
397
+ headers: await this.authHeaders(),
398
+ body: body ?? {},
399
+ noRetry: true
400
+ });
401
+ const obj = isJsonObject(rawBody) ? rawBody : {};
402
+ return {
403
+ status: response.status,
404
+ body: rawBody,
405
+ actions: parseActions(rawBody),
406
+ prize: asWidgetPrize(obj.prize),
407
+ alreadyPlayed: obj.alreadyPlayed === true,
408
+ dispatched: obj.dispatched === true,
409
+ dispatchError: typeof obj.dispatchError === "string" ? obj.dispatchError : void 0,
410
+ widgetType: typeof obj.widgetType === "string" ? obj.widgetType : void 0,
411
+ receivedAt: Date.now()
412
+ };
413
+ }
322
414
  /**
323
415
  * Unified event batch (max 100/request per the backend) — `POST /api/events/v1`.
324
416
  * Records analytics for every event and matches/advances a journey for any
@@ -1086,6 +1178,319 @@ function resolveCookieConfig(opt) {
1086
1178
  return { sameSite, secure, maxAgeDays: o.maxAgeDays ?? 365, domain: o.domain };
1087
1179
  }
1088
1180
 
1181
+ // src/client/widgets/form.ts
1182
+ function collectFields(root) {
1183
+ const fields = {};
1184
+ root.querySelectorAll("[data-xenia-field]").forEach((el) => {
1185
+ const name = el.getAttribute("data-xenia-field");
1186
+ if (!name) return;
1187
+ fields[name] = fieldValue(el);
1188
+ });
1189
+ return fields;
1190
+ }
1191
+ function fieldValue(el) {
1192
+ if (el instanceof HTMLInputElement) {
1193
+ if (el.type === "checkbox") return el.checked ? el.value || "on" : "";
1194
+ if (el.type === "radio") return el.checked ? el.value : "";
1195
+ return el.value;
1196
+ }
1197
+ if (el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement) return el.value;
1198
+ return el.textContent?.trim() ?? "";
1199
+ }
1200
+ function setDisabled(el, disabled) {
1201
+ if (!el) return;
1202
+ if (el instanceof HTMLButtonElement || el instanceof HTMLInputElement || el instanceof HTMLSelectElement || el instanceof HTMLTextAreaElement || el instanceof HTMLFieldSetElement) {
1203
+ el.disabled = disabled;
1204
+ } else if (disabled) {
1205
+ el.setAttribute("aria-disabled", "true");
1206
+ } else {
1207
+ el.removeAttribute("aria-disabled");
1208
+ }
1209
+ }
1210
+ function showError(root, message) {
1211
+ const el = root.querySelector("[data-xenia-error]");
1212
+ if (el) el.textContent = message;
1213
+ }
1214
+ var SUBMIT_STYLE_ID = "xenia-form-submit-style";
1215
+ function ensureSubmitStyles(root) {
1216
+ if (root.querySelector(`#${SUBMIT_STYLE_ID}`)) return;
1217
+ const style = document.createElement("style");
1218
+ style.id = SUBMIT_STYLE_ID;
1219
+ style.textContent = "@keyframes xenia-submit-spin{to{transform:rotate(360deg)}}[data-xenia-submitting]::after{content:'';display:inline-block;width:0.85em;height:0.85em;margin-left:0.5em;vertical-align:-0.15em;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:xenia-submit-spin 0.6s linear infinite}";
1220
+ root.prepend(style);
1221
+ }
1222
+ function setSubmitting(el, submitting) {
1223
+ if (!el) return;
1224
+ if (submitting) el.setAttribute("data-xenia-submitting", "");
1225
+ else el.removeAttribute("data-xenia-submitting");
1226
+ }
1227
+ function fadeOutAndDismiss(root, dismiss) {
1228
+ if (!dismiss) return;
1229
+ const host = root instanceof ShadowRoot ? root.host : root;
1230
+ if (host instanceof HTMLElement) {
1231
+ host.style.transition = "opacity 220ms ease, transform 220ms ease";
1232
+ host.style.opacity = "0";
1233
+ host.style.transform = "scale(0.96)";
1234
+ window.setTimeout(dismiss, 220);
1235
+ } else {
1236
+ dismiss();
1237
+ }
1238
+ }
1239
+ var DEFAULT_SUCCESS_DISPLAY_MS = 900;
1240
+ function revealSuccess(root, form) {
1241
+ const successEl = root.querySelector("[data-xenia-success]");
1242
+ if (!successEl) return false;
1243
+ if (successEl instanceof HTMLElement) successEl.hidden = false;
1244
+ else successEl.removeAttribute("hidden");
1245
+ if (form) {
1246
+ form.hidden = true;
1247
+ } else {
1248
+ root.querySelectorAll("[data-xenia-field], [data-xenia-submit]").forEach((el) => {
1249
+ el.hidden = true;
1250
+ });
1251
+ }
1252
+ return true;
1253
+ }
1254
+ function wireFormSubmit(root, action, ctx) {
1255
+ const form = root.querySelector("form");
1256
+ let submitting = false;
1257
+ ensureSubmitStyles(root);
1258
+ const run = (control, fields) => {
1259
+ if (submitting) return;
1260
+ if (!action.formSubmit) {
1261
+ showError(root, "This form isn't connected yet.");
1262
+ return;
1263
+ }
1264
+ submitting = true;
1265
+ showError(root, "");
1266
+ setDisabled(control, true);
1267
+ setSubmitting(control, true);
1268
+ const startedAt = Date.now();
1269
+ const minDisplayMs = action.formSubmit.successDisplayMs ?? DEFAULT_SUCCESS_DISPLAY_MS;
1270
+ ctx.submitWidgetForm(fields).then(() => {
1271
+ setSubmitting(control, false);
1272
+ revealSuccess(root, form);
1273
+ const wait = Math.max(0, minDisplayMs - (Date.now() - startedAt));
1274
+ window.setTimeout(() => fadeOutAndDismiss(root, ctx.dismiss), wait);
1275
+ }).catch(() => {
1276
+ setSubmitting(control, false);
1277
+ setDisabled(control, false);
1278
+ showError(root, "Something went wrong. Please try again.");
1279
+ }).finally(() => {
1280
+ submitting = false;
1281
+ });
1282
+ };
1283
+ if (form) {
1284
+ form.addEventListener("submit", (ev) => {
1285
+ ev.preventDefault();
1286
+ const formFields = {};
1287
+ new FormData(form).forEach((value, key) => {
1288
+ if (typeof value === "string") formFields[key] = value;
1289
+ });
1290
+ const submitter = ev.submitter ?? form.querySelector('[type="submit"], button:not([type])');
1291
+ run(submitter, { ...collectFields(root), ...formFields });
1292
+ });
1293
+ }
1294
+ root.querySelectorAll("[data-xenia-submit]").forEach((el) => {
1295
+ if (form?.contains(el)) return;
1296
+ el.addEventListener("click", () => run(el, collectFields(root)));
1297
+ });
1298
+ }
1299
+
1300
+ // src/client/widgets/types.ts
1301
+ function escapeHtml(s) {
1302
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1303
+ }
1304
+ function escapeAttr(s) {
1305
+ return escapeHtml(s).replace(/"/g, "&quot;");
1306
+ }
1307
+ function wireCloseAffordances(root, dismiss) {
1308
+ if (dismiss) {
1309
+ const closeEls = root.querySelectorAll(
1310
+ ".xenia-close, [data-xenia-close], [class*='close' i], [id*='close' i], [class*='backdrop' i], [id*='backdrop' i]"
1311
+ );
1312
+ closeEls.forEach((el) => {
1313
+ el.removeAttribute("onclick");
1314
+ el.addEventListener("click", dismiss);
1315
+ });
1316
+ }
1317
+ root.querySelectorAll("[class*='backdrop' i], [id*='backdrop' i]").forEach((el) => {
1318
+ if (el instanceof HTMLElement && el.children.length === 0 && !el.textContent?.trim()) {
1319
+ el.style.opacity = "0.5";
1320
+ }
1321
+ });
1322
+ }
1323
+
1324
+ // src/client/widgets/spin-wheel.ts
1325
+ var WHEEL_SIZE = 260;
1326
+ var RADIUS = WHEEL_SIZE / 2;
1327
+ var CENTER = WHEEL_SIZE / 2;
1328
+ var DEFAULT_COLORS = ["#7c3aed", "#2563eb", "#059669", "#d97706", "#dc2626", "#0891b2"];
1329
+ var SPIN_TRANSITION = "transform 3.2s cubic-bezier(0.15, 0.85, 0.25, 1)";
1330
+ var WHEEL_POINTER_HTML = '<div class="xenia-wheel-pointer" aria-hidden="true"></div>';
1331
+ var REVEAL_TRANSITION_MS = 320;
1332
+ var REVEAL_TRANSITION = `opacity ${REVEAL_TRANSITION_MS}ms ease, transform ${REVEAL_TRANSITION_MS}ms ease`;
1333
+ var REVEAL_PERSPECTIVE_PX = 900;
1334
+ var revealTransform = (scale, depthPx) => `perspective(${REVEAL_PERSPECTIVE_PX}px) translateZ(${depthPx}px) scale(${scale})`;
1335
+ function polarPoint(angleDeg, radius) {
1336
+ const rad = angleDeg * Math.PI / 180;
1337
+ return { x: CENTER + radius * Math.sin(rad), y: CENTER - radius * Math.cos(rad) };
1338
+ }
1339
+ function segmentPath(startAngle, endAngle) {
1340
+ const start = polarPoint(startAngle, RADIUS);
1341
+ const end = polarPoint(endAngle, RADIUS);
1342
+ const largeArc = endAngle - startAngle > 180 ? 1 : 0;
1343
+ return `M ${CENTER},${CENTER} L ${start.x},${start.y} A ${RADIUS},${RADIUS} 0 ${largeArc} 1 ${end.x},${end.y} Z`;
1344
+ }
1345
+ function computeSpinRotation(segmentIndex, segmentCount, extraSpins = 0) {
1346
+ if (segmentCount <= 0) return 0;
1347
+ const segmentAngle = 360 / segmentCount;
1348
+ const centerAngle = segmentIndex * segmentAngle + segmentAngle / 2;
1349
+ const landingAngle = (360 - centerAngle) % 360;
1350
+ return extraSpins * 360 + landingAngle;
1351
+ }
1352
+ function crossFadeReveal(outgoing, incoming) {
1353
+ const outContent = outgoing ? Array.from(outgoing.children) : [];
1354
+ const inContent = incoming ? Array.from(incoming.children) : [];
1355
+ if (incoming) incoming.hidden = false;
1356
+ inContent.forEach((el) => {
1357
+ if (!(el instanceof HTMLElement)) return;
1358
+ el.style.transition = "none";
1359
+ el.style.opacity = "0";
1360
+ el.style.transform = revealTransform(0.94, -60);
1361
+ });
1362
+ inContent.forEach((el) => {
1363
+ if (el instanceof HTMLElement) void el.offsetHeight;
1364
+ });
1365
+ nextFrame(() => {
1366
+ outContent.forEach((el) => {
1367
+ if (!(el instanceof HTMLElement)) return;
1368
+ el.style.transition = REVEAL_TRANSITION;
1369
+ el.style.opacity = "0";
1370
+ el.style.transform = revealTransform(0.94, -60);
1371
+ });
1372
+ inContent.forEach((el) => {
1373
+ if (!(el instanceof HTMLElement)) return;
1374
+ el.style.transition = REVEAL_TRANSITION;
1375
+ el.style.opacity = "1";
1376
+ el.style.transform = revealTransform(1, 0);
1377
+ });
1378
+ });
1379
+ if (outgoing) {
1380
+ setTimeout(() => {
1381
+ outgoing.hidden = true;
1382
+ }, REVEAL_TRANSITION_MS);
1383
+ }
1384
+ }
1385
+ function nextFrame(fn) {
1386
+ if (typeof requestAnimationFrame === "function") requestAnimationFrame(fn);
1387
+ else setTimeout(fn, 0);
1388
+ }
1389
+ function wheelSvg(segments) {
1390
+ const n = segments.length || 1;
1391
+ const segmentAngle = 360 / n;
1392
+ const slices = segments.map((seg, i) => {
1393
+ const start = i * segmentAngle;
1394
+ const end = start + segmentAngle;
1395
+ const color = seg.colorHex || DEFAULT_COLORS[i % DEFAULT_COLORS.length];
1396
+ const labelAngle = start + segmentAngle / 2;
1397
+ const labelPoint = polarPoint(labelAngle, RADIUS * 0.62);
1398
+ return `<path d="${segmentPath(start, end)}" fill="${escapeAttr(color)}" stroke="#fff" stroke-width="1"></path><text x="${labelPoint.x}" y="${labelPoint.y}" fill="#fff" font-size="12" text-anchor="middle" transform="rotate(${labelAngle} ${labelPoint.x} ${labelPoint.y})">${escapeHtml(seg.label)}</text>`;
1399
+ }).join("");
1400
+ return `<svg class="xenia-wheel-svg" viewBox="0 0 ${WHEEL_SIZE} ${WHEEL_SIZE}" width="${WHEEL_SIZE}" height="${WHEEL_SIZE}"><g class="xenia-wheel-dial">${slices}</g><circle class="xenia-wheel-hub" cx="${CENTER}" cy="${CENTER}" r="6"></circle></svg>`;
1401
+ }
1402
+ var spinWheelRenderer = {
1403
+ html(action) {
1404
+ return `<div class="xenia-spin-wheel"><div data-xenia-wheel-face>${action.spinnerHtml ?? ""}</div><div class="xenia-widget-result" data-xenia-wheel-result hidden>${action.winHtml ?? ""}</div><div class="xenia-widget-result" data-xenia-wheel-loss hidden>${action.lossHtml ?? ""}</div></div>`;
1405
+ },
1406
+ wire(root, action, ctx) {
1407
+ wireCloseAffordances(root, ctx.dismiss);
1408
+ const segments = action.segments ?? [];
1409
+ const wheelFace = root.querySelector("[data-xenia-wheel-face]");
1410
+ const spinBtn = root.querySelector("[data-xenia-spin]");
1411
+ const winEl = root.querySelector("[data-xenia-wheel-result]");
1412
+ const lossEl = root.querySelector("[data-xenia-wheel-loss]");
1413
+ const errorEl = root.querySelector("[data-xenia-error]");
1414
+ const slotEl = root.querySelector("[data-xenia-wheel-slot]");
1415
+ if (slotEl) slotEl.insertAdjacentHTML("afterbegin", wheelSvg(segments) + WHEEL_POINTER_HTML);
1416
+ const dial = root.querySelector(".xenia-wheel-dial");
1417
+ if (!spinBtn || !action.formSubmit) return;
1418
+ root.querySelectorAll("[data-xenia-wheel-cta]").forEach((btn) => {
1419
+ btn.addEventListener("click", () => ctx.fireCta());
1420
+ });
1421
+ const revealResult = (prizeLabel, isLoss, canRetry) => {
1422
+ root.querySelectorAll("[data-xenia-wheel-prize]").forEach((el) => {
1423
+ el.textContent = prizeLabel;
1424
+ });
1425
+ const shown = isLoss ? lossEl : winEl;
1426
+ const other = isLoss ? winEl : lossEl;
1427
+ if (other) other.hidden = true;
1428
+ crossFadeReveal(wheelFace, shown);
1429
+ if (!canRetry) {
1430
+ playsExhausted = true;
1431
+ root.querySelectorAll("[data-xenia-spin-again]").forEach((btn) => {
1432
+ btn.hidden = true;
1433
+ });
1434
+ }
1435
+ };
1436
+ let spinning = false;
1437
+ let playsExhausted = false;
1438
+ root.querySelectorAll("[data-xenia-spin-again]").forEach((btn) => {
1439
+ btn.addEventListener("click", () => {
1440
+ if (playsExhausted) return;
1441
+ const shown = winEl && !winEl.hidden ? winEl : lossEl && !lossEl.hidden ? lossEl : null;
1442
+ if (!shown) return;
1443
+ spinning = false;
1444
+ spinBtn.disabled = false;
1445
+ if (errorEl) errorEl.textContent = "";
1446
+ crossFadeReveal(shown, wheelFace);
1447
+ });
1448
+ });
1449
+ spinBtn.addEventListener("click", () => {
1450
+ if (spinning) return;
1451
+ spinning = true;
1452
+ spinBtn.disabled = true;
1453
+ if (errorEl) errorEl.textContent = "";
1454
+ const fields = collectFields(root);
1455
+ ctx.submitWidgetForm(fields).then((response) => {
1456
+ const index = segments.findIndex((s) => s.id === response.prize?.segmentId);
1457
+ const prizeLabel = response.prize?.label ?? segments[index]?.label ?? "";
1458
+ const isLoss = index >= 0 && !!segments[index]?.isLoss;
1459
+ const canRetry = response.alreadyPlayed !== true;
1460
+ if (index < 0 || !dial) {
1461
+ revealResult(prizeLabel, isLoss, canRetry);
1462
+ return;
1463
+ }
1464
+ const extraSpins = 3 + Math.floor(Math.random() * 3);
1465
+ const rotation = computeSpinRotation(index, segments.length || 1, extraSpins);
1466
+ const priorMatch = /rotate\(([-\d.]+)deg\)/.exec(dial.style.transform);
1467
+ const priorRotation = priorMatch ? parseFloat(priorMatch[1]) : 0;
1468
+ dial.style.transition = "none";
1469
+ dial.style.transform = `rotate(${priorRotation % 360}deg)`;
1470
+ void dial.getBoundingClientRect();
1471
+ dial.style.transition = SPIN_TRANSITION;
1472
+ const onTransitionEnd = () => {
1473
+ dial.removeEventListener("transitionend", onTransitionEnd);
1474
+ revealResult(prizeLabel, isLoss, canRetry);
1475
+ };
1476
+ dial.addEventListener("transitionend", onTransitionEnd);
1477
+ nextFrame(() => {
1478
+ dial.style.transform = `rotate(${rotation}deg)`;
1479
+ });
1480
+ }).catch(() => {
1481
+ spinning = false;
1482
+ spinBtn.disabled = false;
1483
+ if (errorEl) errorEl.textContent = "Something went wrong. Please try again.";
1484
+ });
1485
+ });
1486
+ }
1487
+ };
1488
+
1489
+ // src/client/widgets/index.ts
1490
+ var WIDGET_RENDERERS = {
1491
+ "spin-wheel": spinWheelRenderer
1492
+ };
1493
+
1089
1494
  // src/client/renderer.ts
1090
1495
  function resolveTarget(target, root = document) {
1091
1496
  if (!target) return null;
@@ -1143,6 +1548,7 @@ var ActionRenderer = class {
1143
1548
  messageTemplate;
1144
1549
  messageStyles;
1145
1550
  messageComponent;
1551
+ submitWidgetFormFn;
1146
1552
  /** Unmount callbacks for currently-mounted framework components, keyed by their container. */
1147
1553
  mounted = /* @__PURE__ */ new Map();
1148
1554
  constructor(onCta, opts) {
@@ -1150,6 +1556,7 @@ var ActionRenderer = class {
1150
1556
  this.messageTemplate = opts?.messageTemplate;
1151
1557
  this.messageStyles = opts?.messageStyles;
1152
1558
  this.messageComponent = opts?.messageComponent;
1559
+ this.submitWidgetFormFn = opts?.submitWidgetForm;
1153
1560
  }
1154
1561
  /** Apply a list of actions. Returns the count successfully applied. */
1155
1562
  apply(actions) {
@@ -1232,7 +1639,8 @@ ${this.messageStyles}` : STYLES;
1232
1639
  const wrap = document.createElement("div");
1233
1640
  const posClass = this.positionClass(action.type, action.position);
1234
1641
  const customBgClass = action.html !== void 0 ? " xenia-custom-bg" : "";
1235
- wrap.className = `xenia-msg xenia-${action.type}${posClass ? ` ${posClass}` : ""}${customBgClass}`;
1642
+ const noOverlayClass = action.style?.hideOverlay ? " xenia-no-overlay" : "";
1643
+ wrap.className = `xenia-msg xenia-${action.type}${posClass ? ` ${posClass}` : ""}${customBgClass}${noOverlayClass}`;
1236
1644
  shadow.appendChild(wrap);
1237
1645
  const dismiss = () => {
1238
1646
  this.unmount(wrap);
@@ -1245,7 +1653,10 @@ ${this.messageStyles}` : STYLES;
1245
1653
  this.wireCard(wrap, action, dismiss);
1246
1654
  }
1247
1655
  if (action.dismissAfterMs && action.dismissAfterMs > 0) {
1248
- setTimeout(dismiss, action.dismissAfterMs);
1656
+ const timer = setTimeout(dismiss, action.dismissAfterMs);
1657
+ const cancelAutoDismiss = () => clearTimeout(timer);
1658
+ wrap.addEventListener("click", cancelAutoDismiss, { once: true });
1659
+ wrap.addEventListener("focusin", cancelAutoDismiss, { once: true });
1249
1660
  }
1250
1661
  return true;
1251
1662
  }
@@ -1289,38 +1700,32 @@ ${this.messageStyles}` : STYLES;
1289
1700
  return "";
1290
1701
  }
1291
1702
  cardHtml(action, variant) {
1703
+ const widget = action.widgetType ? WIDGET_RENDERERS[action.widgetType] : void 0;
1704
+ if (widget) return widget.html(action, variant);
1292
1705
  if (action.html !== void 0) return wrapCustomHtml(action.html, variant);
1293
1706
  if (this.messageTemplate) {
1294
1707
  const ctx = {
1295
1708
  action,
1296
1709
  variant,
1297
- escapeHtml,
1298
- escapeAttr
1710
+ escapeHtml: escapeHtml2,
1711
+ escapeAttr: escapeAttr2
1299
1712
  };
1300
1713
  return this.messageTemplate(ctx);
1301
1714
  }
1302
- const img = action.imageUrl ? `<img class="xenia-img" src="${escapeAttr(action.imageUrl)}" alt="" />` : "";
1303
- const title = action.title ? `<div class="xenia-title">${escapeHtml(action.title)}</div>` : "";
1304
- const msg = action.message ? `<div class="xenia-body">${escapeHtml(action.message)}</div>` : "";
1305
- const cta = action.cta ? `<button class="xenia-cta" type="button">${escapeHtml(action.cta.label)}</button>` : "";
1715
+ const img = action.imageUrl ? `<img class="xenia-img" src="${escapeAttr2(action.imageUrl)}" alt="" />` : "";
1716
+ const title = action.title ? `<div class="xenia-title">${escapeHtml2(action.title)}</div>` : "";
1717
+ const msg = action.message ? `<div class="xenia-body">${escapeHtml2(action.message)}</div>` : "";
1718
+ const cta = action.cta ? `<button class="xenia-cta" type="button">${escapeHtml2(action.cta.label)}</button>` : "";
1306
1719
  const close = variant === "inline" ? "" : `<button class="xenia-close" type="button" aria-label="Close">\xD7</button>`;
1307
1720
  return `<div class="xenia-card">${close}${img}<div class="xenia-content">${title}${msg}${cta}</div></div>`;
1308
1721
  }
1309
1722
  wireCard(root, action, dismiss) {
1310
- if (dismiss) {
1311
- const closeEls = root.querySelectorAll(
1312
- ".xenia-close, [data-xenia-close], [class*='close' i], [id*='close' i], [class*='backdrop' i], [id*='backdrop' i]"
1313
- );
1314
- closeEls.forEach((el) => {
1315
- el.removeAttribute("onclick");
1316
- el.addEventListener("click", dismiss);
1317
- });
1723
+ const widget = action.widgetType ? WIDGET_RENDERERS[action.widgetType] : void 0;
1724
+ if (widget) {
1725
+ widget.wire(root, action, this.buildWidgetCtx(action, dismiss));
1726
+ return;
1318
1727
  }
1319
- root.querySelectorAll("[class*='backdrop' i], [id*='backdrop' i]").forEach((el) => {
1320
- if (el instanceof HTMLElement && el.children.length === 0 && !el.textContent?.trim()) {
1321
- el.style.opacity = "0.5";
1322
- }
1323
- });
1728
+ wireCloseAffordances(root, dismiss);
1324
1729
  const ctaBtn = root.querySelector(".xenia-cta, [data-xenia-cta]");
1325
1730
  if (ctaBtn && action.cta) {
1326
1731
  ctaBtn.addEventListener("click", () => {
@@ -1329,6 +1734,29 @@ ${this.messageStyles}` : STYLES;
1329
1734
  dismiss?.();
1330
1735
  });
1331
1736
  }
1737
+ wireFormSubmit(root, action, this.buildWidgetCtx(action, dismiss));
1738
+ }
1739
+ /** Build the imperative hooks (`dismiss`/`fireCta`/`submitWidgetForm`) handed to a widget's `wire()`. */
1740
+ buildWidgetCtx(action, dismiss) {
1741
+ const idempotencyKey = generateUlid();
1742
+ return {
1743
+ dismiss,
1744
+ fireCta: () => {
1745
+ if (action.cta?.event) this.onCta?.(action.cta.event, action.cta);
1746
+ if (action.cta?.url) window.location.assign(action.cta.url);
1747
+ dismiss?.();
1748
+ },
1749
+ submitWidgetForm: (fields) => {
1750
+ if (!action.formSubmit || !this.submitWidgetFormFn) {
1751
+ return Promise.reject(
1752
+ new Error(
1753
+ "xenia: this action has no formSubmit config, or no submitWidgetForm handler is wired (construct the ActionRenderer via XeniaClient to get one)"
1754
+ )
1755
+ );
1756
+ }
1757
+ return this.submitWidgetFormFn(action.formSubmit, fields, { idempotencyKey });
1758
+ }
1759
+ };
1332
1760
  }
1333
1761
  };
1334
1762
  function wrapCustomHtml(html, variant) {
@@ -1337,11 +1765,11 @@ function wrapCustomHtml(html, variant) {
1337
1765
  }
1338
1766
  return `<div class="xenia-custom-html"><style>.xenia-custom-html{position:relative}.xenia-custom-html>*{position:static!important;inset:auto!important;top:auto!important;right:auto!important;bottom:auto!important;left:auto!important}</style>${html}</div>`;
1339
1767
  }
1340
- function escapeHtml(s) {
1768
+ function escapeHtml2(s) {
1341
1769
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1342
1770
  }
1343
- function escapeAttr(s) {
1344
- return escapeHtml(s).replace(/"/g, "&quot;");
1771
+ function escapeAttr2(s) {
1772
+ return escapeHtml2(s).replace(/"/g, "&quot;");
1345
1773
  }
1346
1774
  var STYLES = `
1347
1775
  :host { all: initial; }
@@ -1358,12 +1786,14 @@ var STYLES = `
1358
1786
  .xenia-modal { inset: 0; display: flex; align-items: center; justify-content: center;
1359
1787
  background: var(--xenia-modal-backdrop, rgba(0,0,0,.12)); }
1360
1788
  .xenia-modal.xenia-custom-bg { background: transparent; }
1789
+ .xenia-modal.xenia-no-overlay { background: transparent; }
1361
1790
  .xenia-card { position: relative; background: var(--xenia-card-bg, #fff); color: var(--xenia-card-color, #111);
1362
1791
  border-radius: var(--xenia-card-radius, 12px); box-shadow: var(--xenia-card-shadow, 0 10px 40px rgba(0,0,0,.18));
1363
1792
  padding: var(--xenia-card-padding, 16px 18px); display: flex; gap: var(--xenia-card-gap, 12px);
1364
1793
  align-items: center; }
1365
1794
  .xenia-banner .xenia-card { border-radius: var(--xenia-banner-card-radius, 0); justify-content: center; }
1366
1795
  .xenia-modal .xenia-card { max-width: var(--xenia-modal-max-width, 440px); width: calc(100% - 32px); }
1796
+ .xenia-card.xenia-widget { flex-direction: column; align-items: center; text-align: center; }
1367
1797
  .xenia-img { width: var(--xenia-img-size, 56px); height: var(--xenia-img-size, 56px); object-fit: cover;
1368
1798
  border-radius: var(--xenia-img-radius, 8px); }
1369
1799
  .xenia-title { font-weight: var(--xenia-title-weight, 600); font-size: var(--xenia-title-size, 15px);
@@ -1375,6 +1805,38 @@ var STYLES = `
1375
1805
  font-size: var(--xenia-cta-size, 14px); cursor: pointer; }
1376
1806
  .xenia-close { position: absolute; top: 6px; right: 8px; background: none; border: 0;
1377
1807
  font-size: var(--xenia-close-size, 20px); line-height: 1; cursor: pointer; color: var(--xenia-close-color, #999); }
1808
+ .xenia-wheel-dial { transform-box: fill-box; transform-origin: center; }
1809
+ .xenia-wheel-hub { fill: var(--xenia-wheel-pointer-color, #111); }
1810
+ .xenia-wheel-wrap { position: relative; display: inline-block; }
1811
+ .xenia-wheel-pointer { position: absolute; top: -6px; left: 50%; transform: translateX(-50%);
1812
+ width: 0; height: 0; border-left: 9px solid transparent; border-right: 9px solid transparent;
1813
+ border-top: 14px solid var(--xenia-wheel-pointer-color, #111); pointer-events: none; }
1814
+ .xenia-wheel-spin { margin-top: 10px; background: var(--xenia-cta-bg, #111); color: var(--xenia-cta-color, #fff);
1815
+ border: 0; border-radius: var(--xenia-cta-radius, 8px); padding: var(--xenia-cta-padding, 8px 14px);
1816
+ font-size: var(--xenia-cta-size, 14px); font-family: inherit; cursor: pointer; }
1817
+ .xenia-wheel-spin:disabled { opacity: 0.6; cursor: default; }
1818
+ /* No animation/transform here \u2014 spin-wheel's win/loss screens are ALWAYS full
1819
+ custom HTML now (winHtml/lossHtml), never this class's own generated icon/title/prize/cta
1820
+ content (those sub-classes below are unreachable dead CSS, kept only for backwards-compat with
1821
+ any already-saved artifact that might still reference them). A transform on THIS wrapper
1822
+ would make it the CSS containing block for any fixed/absolute-positioned descendant the
1823
+ author's own HTML uses (a real, common case \u2014 a "full-screen overlay" win/loss design) \u2014 the
1824
+ fixed child would then size/position itself relative to this wrapper's own small, in-flow,
1825
+ often off-center box instead of the true browser viewport, visibly popping in from/toward
1826
+ whatever corner the wrapper happens to sit at instead of scaling from the real screen center.
1827
+ spin-wheel.ts's crossFadeReveal owns the actual reveal transition (applied to the author's own
1828
+ top-level element, never this wrapper) \u2014 this class stays a bare, transform-free layout box. */
1829
+ .xenia-widget-result { display: flex; flex-direction: column; align-items: center; gap: 4px;
1830
+ padding: 8px 4px 2px; text-align: center; }
1831
+ .xenia-widget-result[hidden] { display: none; }
1832
+ .xenia-widget-result-icon { font-size: 40px; line-height: 1; }
1833
+ .xenia-widget-result-title { font-weight: var(--xenia-title-weight, 700); font-size: var(--xenia-title-size, 17px); }
1834
+ .xenia-widget-result-prize { font-weight: 600; font-size: 15px; color: var(--xenia-cta-bg, #111);
1835
+ background: var(--xenia-result-prize-bg, rgba(0,0,0,.06)); border-radius: var(--xenia-cta-radius, 8px);
1836
+ padding: 6px 14px; }
1837
+ .xenia-widget-result-cta { margin-top: 8px; background: var(--xenia-cta-bg, #111); color: var(--xenia-cta-color, #fff);
1838
+ border: 0; border-radius: var(--xenia-cta-radius, 8px); padding: var(--xenia-cta-padding, 8px 14px);
1839
+ font-size: var(--xenia-cta-size, 14px); font-family: inherit; cursor: pointer; }
1378
1840
  `;
1379
1841
 
1380
1842
  // src/client/xenia-client.ts
@@ -1399,7 +1861,8 @@ var XeniaClient = class {
1399
1861
  this.renderer = new ActionRenderer((event, cta) => this.onCtaEvent(event, cta), {
1400
1862
  messageTemplate: options.messageTemplate,
1401
1863
  messageStyles: options.messageStyles,
1402
- messageComponent: options.messageComponent
1864
+ messageComponent: options.messageComponent,
1865
+ submitWidgetForm: (submit, fields, subOpts) => this.submitWidgetForm(submit, fields, subOpts)
1403
1866
  });
1404
1867
  this.consentState = { ...options.consent };
1405
1868
  this.analyticsQueue = new AnalyticsQueue({
@@ -1671,6 +2134,55 @@ var XeniaClient = class {
1671
2134
  getResponse(key) {
1672
2135
  return this.responses.get(key);
1673
2136
  }
2137
+ /**
2138
+ * Submit a widget's captured form values (standard/custom popup submit, or a spin-wheel/
2139
+ * spin-wheel's resolve request) and apply any returned `xeniaActions`, exactly like
2140
+ * {@link request}.
2141
+ *
2142
+ * **Endpoint selection is config-driven, not SDK-decided** (per the cross-repo contract): a
2143
+ * `flowRef` (present only when `mode === "journey" && !requiresResolve` — the common
2144
+ * plain-popup case) bypasses the resolve endpoint entirely and POSTs straight to the existing
2145
+ * public `/flow` fast path; otherwise this POSTs to `/widget-submissions` via `bindingRef`. The
2146
+ * SDK is agnostic to *why* — it just follows whichever ref field the backend populated.
2147
+ *
2148
+ * The full ambient-context parity list {@link request}/`withVisitor()` already build
2149
+ * (visitorId, deviceId, url, referrer, path, query, `utm*`) rides on every call, plus `fields`
2150
+ * and `submit.mode`/the resolved ref, relayed verbatim/uninterpreted — the SDK never branches
2151
+ * on `mode`'s value itself, that's server-side.
2152
+ *
2153
+ * `opts.idempotencyKey` defaults to a freshly generated ULID; pass the SAME key back in on a
2154
+ * retried submit of the same interaction so a network retry can't double-fire a journey or
2155
+ * double-resolve a prize server-side.
2156
+ */
2157
+ async submitWidgetForm(submit, fields, opts) {
2158
+ const ctx = this.identity.collectContext();
2159
+ const idempotencyKey = opts?.idempotencyKey ?? generateUlid();
2160
+ const ref = submit.flowRef ?? submit.bindingRef;
2161
+ const ambient = {
2162
+ visitorId: this.resolveVisitorId(),
2163
+ deviceId: this.identity.getDeviceId() ?? void 0,
2164
+ idempotencyKey,
2165
+ mode: submit.mode,
2166
+ ref,
2167
+ url: ctx.url,
2168
+ referrer: ctx.referrer,
2169
+ path: ctx.path,
2170
+ query: ctx.query,
2171
+ utmSource: ctx.utmSource,
2172
+ utmMedium: ctx.utmMedium,
2173
+ utmCampaign: ctx.utmCampaign,
2174
+ utmContent: ctx.utmContent,
2175
+ utmId: ctx.utmId
2176
+ };
2177
+ const response = submit.flowRef ? await this.api.webhook(submit.flowRef, compact({ ...ambient, ...fields }), "POST") : await this.api.submitWidget(
2178
+ submit.bindingRef ?? "",
2179
+ compact({ ...ambient, fields })
2180
+ );
2181
+ this.emit("response", { triggerId: ref, response });
2182
+ const apply = opts?.apply ?? this.options.autoApplyActions !== false;
2183
+ if (apply && response.actions.length) this.applyActions(response.actions);
2184
+ return response;
2185
+ }
1674
2186
  // ── Imperative render helpers ─────────────────────────────────────────────────
1675
2187
  swapContent(target, content) {
1676
2188
  return swapContent(target, content);
@@ -1780,6 +2292,6 @@ function extractContentSwaps(body) {
1780
2292
  return Array.isArray(swaps) ? swaps : void 0;
1781
2293
  }
1782
2294
 
1783
- export { ActionRenderer, AnalyticsQueue, AutoTracker, Identity, TokenProvider, XeniaClient, createXeniaClient, extractContentSwaps, hideContent, parseActions, parseDataAttribute, readSlotMeta, resolveTarget, showContent, spliceSlots, swapContent };
2295
+ export { ActionRenderer, AnalyticsQueue, AutoTracker, Identity, TokenProvider, WIDGET_RENDERERS, XeniaClient, collectFields, computeSpinRotation, createXeniaClient, extractContentSwaps, hideContent, parseActions, parseDataAttribute, readSlotMeta, resolveTarget, showContent, spliceSlots, swapContent, wireFormSubmit };
1784
2296
  //# sourceMappingURL=index.js.map
1785
2297
  //# sourceMappingURL=index.js.map