@dataships/launcher 0.1.1 → 0.2.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.
@@ -1,4 +1,4 @@
1
1
  {
2
- "launcher.js": "sha384-NtsTZ3C4YYlHLFrA9Vhx+BCmNFi87xmxKTYVCpAu5c/Py1iksefAd23uE2cp4+6C",
3
- "modules/alia-0.1.1.js": "sha384-G7MwLc6JmBZs6MoTSvHuVj98jJqGIw8lyrn6l2QB6wxmo5/IuSeoFJhgJWhA31Pt"
2
+ "launcher.js": "sha384-G6itJsfiMshc5Sdg9NdFuI8cJxq4WCMsU19gsN9NxviUC7rxTApGRZ8lgvqXY5aG",
3
+ "modules/alia-0.2.0.js": "sha384-jW/3r9fyQjBcLKnIiLSbASojfBstddKdOxHnOUtnHRvJBbaMuD3yDJprA0GaLkQv"
4
4
  }
package/dist/launcher.js CHANGED
@@ -12,6 +12,19 @@
12
12
  // src/elementsApi.ts
13
13
  var ELEMENTS_PATH = "/v1/elements";
14
14
  var isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
15
+ var parseChannels = (value) => {
16
+ if (value === void 0) return [];
17
+ if (!Array.isArray(value)) return null;
18
+ const channels = [];
19
+ for (const entry of value) {
20
+ if (typeof entry !== "object" || entry === null) return null;
21
+ const { channel, subscriptionType } = entry;
22
+ if (!isNonEmptyString(channel) || !isNonEmptyString(subscriptionType))
23
+ return null;
24
+ channels.push({ channel, subscriptionType });
25
+ }
26
+ return channels;
27
+ };
15
28
  var parseElements = (body) => {
16
29
  if (typeof body !== "object" || body === null) return null;
17
30
  const { datashipsSessionId, token, elements } = body;
@@ -20,13 +33,15 @@
20
33
  const refs = [];
21
34
  for (const element of elements) {
22
35
  if (typeof element !== "object" || element === null) return null;
23
- const { type, id } = element;
36
+ const { type, id, channels } = element;
24
37
  if (!isNonEmptyString(type) || !isNonEmptyString(id)) return null;
25
- refs.push({ type, id });
38
+ const parsedChannels = parseChannels(channels);
39
+ if (!parsedChannels) return null;
40
+ refs.push({ type, id, channels: parsedChannels });
26
41
  }
27
42
  return { datashipsSessionId, token, elements: refs };
28
43
  };
29
- var idsOfType = (data, type) => data.elements.filter((element) => element.type === type).map((element) => element.id);
44
+ var elementsOfType = (data, type) => data.elements.filter((element) => element.type === type);
30
45
  var fetchElements = async (fetchFn, baseUrl, publicKey) => {
31
46
  try {
32
47
  const response = await fetchFn(`${baseUrl}${ELEMENTS_PATH}`, {
@@ -132,7 +147,7 @@
132
147
  var MODULES = [
133
148
  {
134
149
  type: "ALIA_FORM",
135
- file: `modules/alia-${"0.1.1"}.js`,
150
+ file: `modules/alia-${"0.2.0"}.js`,
136
151
  watch: watchAlia
137
152
  }
138
153
  ];
@@ -154,7 +169,7 @@
154
169
  if (!config) return;
155
170
  const guard = win;
156
171
  if (guard.__datashipsLauncher) return;
157
- guard.__datashipsLauncher = { version: "0.1.1" };
172
+ guard.__datashipsLauncher = { version: "0.2.0" };
158
173
  const modules = env.modules ?? MODULES;
159
174
  const importModule = env.importModule ?? defaultImport;
160
175
  const load = (definition, context, beforeStart) => startModule(importModule, config, definition, context, beforeStart);
@@ -165,7 +180,7 @@
165
180
  preview: true,
166
181
  token: null,
167
182
  datashipsSessionId: null,
168
- campaignIds: [],
183
+ elements: [],
169
184
  events: []
170
185
  };
171
186
  await Promise.all(modules.map((definition) => load(definition, context)));
@@ -177,8 +192,10 @@
177
192
  }));
178
193
  const outcome = await resolveElements(env, config);
179
194
  for (const { definition, watch } of watched) {
180
- const campaignIds = outcome.status === "ok" ? idsOfType(outcome.data, definition.type) : [];
181
- if (outcome.status !== "ok" || campaignIds.length === 0) {
195
+ const elements = outcome.status === "ok" ? elementsOfType(outcome.data, definition.type).map(
196
+ ({ id, channels }) => ({ id, channels })
197
+ ) : [];
198
+ if (outcome.status !== "ok" || elements.length === 0) {
182
199
  watch.stop();
183
200
  continue;
184
201
  }
@@ -188,7 +205,7 @@
188
205
  preview: false,
189
206
  token: outcome.data.token,
190
207
  datashipsSessionId: outcome.data.datashipsSessionId,
191
- campaignIds,
208
+ elements,
192
209
  events: watch.events
193
210
  };
194
211
  void watch.present.then(() => load(definition, context, watch.stop));
@@ -483,7 +483,7 @@ var DatashipsClient = class {
483
483
  *
484
484
  * `user.firstName` / `lastName` are required (the backend refuses a blank
485
485
  * name; the SDK refuses it before sending), unless the adapter's
486
- * `submitRequiresUser` is false, as on `AliaFormAdapter`: then `user` may be
486
+ * `submitRequiresUser` is false, as on the Alia form adapters: then `user` may be
487
487
  * omitted and the submit goes without it. The beacon defaults to the
488
488
  * adapter's own `datashipsSessionId`, which is then discarded once the
489
489
  * submit is accepted. Idempotent on the backend; a
@@ -585,7 +585,7 @@ post_fn = async function(args) {
585
585
  const staticHeaders = {
586
586
  // The marker lets the backend tell an exposed key in a page from a genuine server call.
587
587
  "X-Dataships-App": `${this.app} (SDK: ${this.adapter.name}${this.isUnsafeServerKey ? `; ${UNSAFE_SERVER_KEY_APP_MARKER}` : ""})`,
588
- "X-Dataships-Version": `${this.version} (SDK: ${"2.1.0"})`
588
+ "X-Dataships-Version": `${this.version} (SDK: ${"2.4.0"})`
589
589
  };
590
590
  return postJson({
591
591
  url: `${this.baseUrl}${args.path}`,
@@ -1338,9 +1338,14 @@ var BASE_STYLES = (
1338
1338
  }
1339
1339
  .link:focus-visible { outline: 2px solid var(--ds-color-primary, #1f6feb); outline-offset: 2px; border-radius: 2px; }
1340
1340
 
1341
- .text { margin: 0; }
1342
1341
  .description { margin: 0; font-size: 0.875em; color: var(--ds-color-text-secondary, #6b7280); }
1343
1342
 
1343
+ /* Styled by a class of the host page (\`className\`): the copy takes what the element has. */
1344
+ :host([data-host-styled]) .description { font-size: var(--ds-font-size, inherit); color: var(--ds-color-text-secondary, inherit); }
1345
+ :host([data-host-styled]) .root .link { color: var(--ds-color-primary, inherit); }
1346
+ /* The modal has its own background, so it must not take the page's text styles. */
1347
+ :host([data-host-styled]) .modal { color: var(--ds-color-text, #111827); font-size: 1rem; text-align: start; }
1348
+
1344
1349
  .modal {
1345
1350
  max-width: min(560px, 90vw);
1346
1351
  padding: 0;
@@ -1362,10 +1367,10 @@ var BASE_STYLES = (
1362
1367
  `
1363
1368
  );
1364
1369
  var WORDS = {
1365
- en: { clickHere: "Click here", privacyPolicy: "Privacy Policy", consent: "consent", object: "object", optIn: "opt in", optOut: "opt out" },
1366
- es: { clickHere: "Haz clic aqu\xED", privacyPolicy: "Pol\xEDtica de privacidad", consent: "consentimiento", object: "oponerte", optIn: "inscribirte", optOut: "no quieres recibirlo" },
1367
- de: { clickHere: "Klicken Sie hier", privacyPolicy: "Datenschutzrichtlinie", consent: "Zustimmung", object: "protestieren", optIn: "zuzustimmen", optOut: "widersprechen" },
1368
- fr: { clickHere: "Cliquez ici", privacyPolicy: "Politique de confidentialit\xE9", consent: "consentement", object: "d\xE9sapprouver", optIn: "accepter", optOut: "refuser" }
1370
+ en: { clickHere: "Click here", privacyPolicy: "Privacy Policy", termsOfService: "Terms of Service", consent: "consent", object: "object", optIn: "opt in", optOut: "opt out" },
1371
+ es: { clickHere: "Haz clic aqu\xED", privacyPolicy: "Pol\xEDtica de privacidad", termsOfService: "Condiciones del servicio", consent: "consentimiento", object: "oponerte", optIn: "inscribirte", optOut: "no quieres recibirlo" },
1372
+ de: { clickHere: "Klicken Sie hier", privacyPolicy: "Datenschutzrichtlinie", termsOfService: "Servicebedingungen", consent: "Zustimmung", object: "protestieren", optIn: "zuzustimmen", optOut: "widersprechen" },
1373
+ fr: { clickHere: "Cliquez ici", privacyPolicy: "Politique de confidentialit\xE9", termsOfService: "Conditions d'utilisation", consent: "consentement", object: "d\xE9sapprouver", optIn: "accepter", optOut: "refuser" }
1369
1374
  };
1370
1375
  var escapeRegExp3 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1371
1376
  var formatCopy = (text, locale, rules) => {
@@ -1383,10 +1388,11 @@ var formatCopy = (text, locale, rules) => {
1383
1388
  var ALLOWED_TAGS = /* @__PURE__ */ new Set(["H1", "H2", "H3", "P", "BR", "UL", "OL", "LI", "A", "STRONG", "B", "EM", "I"]);
1384
1389
  var DROPPED_TAGS = /* @__PURE__ */ new Set(["SCRIPT", "STYLE", "TEMPLATE", "IFRAME", "OBJECT", "EMBED", "NOSCRIPT", "SVG", "MATH", "TITLE", "TEXTAREA", "SELECT"]);
1385
1390
  var ALLOWED_PROTOCOLS = /* @__PURE__ */ new Set(["https:", "mailto:"]);
1386
- var safeHref = (href) => {
1391
+ var CONFIG_URL_PROTOCOLS = /* @__PURE__ */ new Set(["https:", "http:", "mailto:"]);
1392
+ var safeHref = (href, protocols = ALLOWED_PROTOCOLS) => {
1387
1393
  if (!href) return null;
1388
1394
  try {
1389
- return ALLOWED_PROTOCOLS.has(new URL(href.trim()).protocol) ? href.trim() : null;
1395
+ return protocols.has(new URL(href.trim()).protocol) ? href.trim() : null;
1390
1396
  } catch {
1391
1397
  return null;
1392
1398
  }
@@ -1507,21 +1513,20 @@ _shadow = /* @__PURE__ */ new WeakMap();
1507
1513
  _root = /* @__PURE__ */ new WeakMap();
1508
1514
  _onConsentChange = /* @__PURE__ */ new WeakMap();
1509
1515
  _DatashipsWidget_instances = /* @__PURE__ */ new WeakSet();
1510
- renderInto_fn = function(response, { page, locale = "en", heading = "Email marketing preferences" }) {
1516
+ renderInto_fn = function(response, { page, locale = "en", heading = "Email marketing preferences", channel = "EMAIL" }) {
1511
1517
  __privateGet4(this, _root)?.remove();
1512
1518
  __privateSet4(this, _root, null);
1513
- const item = (response?.consents ?? []).find((c) => c.channel === "EMAIL");
1519
+ const item = (response?.consents ?? []).find((c) => c.channel === channel);
1514
1520
  if (!item) {
1515
1521
  this.removeAttribute("data-visible");
1516
1522
  return;
1517
1523
  }
1518
1524
  const cfg = item.widgetConfig ?? {};
1519
- const textOnly = page === "form";
1520
- const showCheckbox = !textOnly && item.consentType !== "NONE" && !!cfg.text;
1521
- const showText = textOnly && !!cfg.text;
1525
+ const description = page === "form" ? cfg.consentDescription || cfg.text : cfg.consentDescription;
1526
+ const showCheckbox = page !== "form" && item.consentType !== "NONE" && !!cfg.text;
1522
1527
  const isControl = !cfg.consentDescription && !cfg.marketingInformation;
1523
1528
  const boxed = page === "confirmation";
1524
- if (!showCheckbox && !showText && !cfg.consentDescription) {
1529
+ if (!showCheckbox && !description) {
1525
1530
  this.removeAttribute("data-visible");
1526
1531
  return;
1527
1532
  }
@@ -1535,6 +1540,10 @@ renderInto_fn = function(response, { page, locale = "en", heading = "Email marke
1535
1540
  modal?.setAttribute("open", "");
1536
1541
  }
1537
1542
  };
1543
+ const link = (text, href) => {
1544
+ const safe = safeHref(href ?? null, CONFIG_URL_PROTOCOLS);
1545
+ return safe ? el("a", { className: "link", text, attrs: { href: safe, target: "_blank", rel: "noreferrer noopener" } }) : document.createTextNode(text);
1546
+ };
1538
1547
  const rules = (policyURL) => ({
1539
1548
  consent: (m) => el("strong", { text: m }),
1540
1549
  object: (m) => el("strong", { text: m }),
@@ -1546,7 +1555,9 @@ renderInto_fn = function(response, { page, locale = "en", heading = "Email marke
1546
1555
  b.addEventListener("click", openModal);
1547
1556
  return b;
1548
1557
  },
1549
- privacyPolicy: (m) => policyURL ? el("a", { className: "link", text: m, attrs: { href: policyURL, target: "_blank", rel: "noreferrer noopener" } }) : document.createTextNode(m)
1558
+ privacyPolicy: (m) => link(m, policyURL),
1559
+ // SMS copy also names the mobile terms; email copy keeps linking the privacy policy only.
1560
+ ...channel === "SMS" ? { termsOfService: (m) => link(m, cfg.mobileTermsOfServiceURL) } : {}
1550
1561
  });
1551
1562
  if (showCheckbox) {
1552
1563
  const id = "dataships-consent-checkbox";
@@ -1570,11 +1581,8 @@ renderInto_fn = function(response, { page, locale = "en", heading = "Email marke
1570
1581
  });
1571
1582
  root.append(el("div", { className: "consent" }, [checkbox, label]));
1572
1583
  }
1573
- if (showText) {
1574
- root.append(el("p", { className: "text" }, formatCopy(cfg.text, locale, rules(cfg.policyURL))));
1575
- }
1576
- if (cfg.consentDescription) {
1577
- root.append(el("p", { className: "description" }, formatCopy(cfg.consentDescription, locale, rules(cfg.policyURL))));
1584
+ if (description) {
1585
+ root.append(el("p", { className: "description" }, formatCopy(description, locale, rules(cfg.policyURL))));
1578
1586
  }
1579
1587
  if (modal) root.append(modal);
1580
1588
  __privateGet4(this, _shadow).append(root);
@@ -1633,7 +1641,7 @@ var createSdkClient = (opts) => {
1633
1641
  ...preview ? {} : opts.unsafeServerKey ? { auth: { unsafeServerKey: opts.unsafeServerKey } } : { auth: { publicKey: opts.publicKey, token: opts.token } },
1634
1642
  env: opts.env ?? "production",
1635
1643
  app: ELEMENTS_APP_NAME,
1636
- version: "2.1.0",
1644
+ version: "2.5.0",
1637
1645
  adapter,
1638
1646
  ...opts.baseUrl ? { baseUrl: opts.baseUrl } : {},
1639
1647
  ...opts.fetch ? { fetch: opts.fetch } : {}
@@ -1654,6 +1662,7 @@ var _client;
1654
1662
  var _log;
1655
1663
  var _emit;
1656
1664
  var _heartbeat;
1665
+ var _identifierType;
1657
1666
  var _onResponse;
1658
1667
  var _stopHeartbeat;
1659
1668
  var Session = class {
@@ -1661,10 +1670,12 @@ var Session = class {
1661
1670
  this.response = null;
1662
1671
  this.ids = { consentSessionId: null };
1663
1672
  this.lastIdentifier = null;
1673
+ this.ok = false;
1664
1674
  __privateAdd4(this, _client);
1665
1675
  __privateAdd4(this, _log);
1666
1676
  __privateAdd4(this, _emit);
1667
1677
  __privateAdd4(this, _heartbeat);
1678
+ __privateAdd4(this, _identifierType);
1668
1679
  __privateAdd4(this, _onResponse);
1669
1680
  __privateAdd4(this, _stopHeartbeat, () => {
1670
1681
  });
@@ -1672,14 +1683,22 @@ var Session = class {
1672
1683
  __privateSet4(this, _log, opts.log);
1673
1684
  __privateSet4(this, _emit, opts.emit);
1674
1685
  __privateSet4(this, _heartbeat, opts.heartbeat);
1686
+ __privateSet4(this, _identifierType, opts.identifierType ?? "EMAIL");
1675
1687
  __privateSet4(this, _onResponse, opts.onResponse);
1676
1688
  }
1677
- /** Open or update the session. Never rejects: a failure is logged and renders nothing. */
1678
- async upsert(identifier) {
1689
+ /**
1690
+ * Open or update the session. Never rejects: a failure is logged and renders nothing.
1691
+ * With `keepOnFailure` a failure leaves the session, its heartbeat and what is rendered
1692
+ * as they were: the session opened before is still there, and so is the text the
1693
+ * visitor is reading.
1694
+ */
1695
+ async upsert(identifier, { keepOnFailure = false } = {}) {
1696
+ const previousIdentifier = this.lastIdentifier;
1679
1697
  this.lastIdentifier = identifier;
1680
1698
  const who = identifier ? "set" : "anonymous";
1681
1699
  try {
1682
- this.response = await __privateGet4(this, _client).upsertSession({ identifierType: "EMAIL", ...identifier ? { identifier } : {} });
1700
+ this.response = await __privateGet4(this, _client).upsertSession({ identifierType: __privateGet4(this, _identifierType), ...identifier ? { identifier } : {} });
1701
+ this.ok = true;
1683
1702
  const consents = this.response.consents.map((c) => `${c.channel}:${c.consentType}`);
1684
1703
  __privateGet4(this, _log).call(this, "upsert ok", { consentSessionId: this.response.consentSessionId, consents, identifier: who });
1685
1704
  __privateGet4(this, _emit).call(this, "dataships:upsert", { ok: true, consentSessionId: this.response.consentSessionId, consents, identifier: who });
@@ -1687,6 +1706,11 @@ var Session = class {
1687
1706
  const error = describeError(e);
1688
1707
  __privateGet4(this, _log).call(this, "upsert failed", error);
1689
1708
  __privateGet4(this, _emit).call(this, "dataships:upsert", { ok: false, consentSessionId: null, consents: [], identifier: who, error });
1709
+ this.ok = false;
1710
+ if (keepOnFailure) {
1711
+ this.lastIdentifier = previousIdentifier;
1712
+ return;
1713
+ }
1690
1714
  this.response = null;
1691
1715
  }
1692
1716
  this.ids = { consentSessionId: this.response?.consentSessionId ?? null };
@@ -1720,23 +1744,31 @@ _client = /* @__PURE__ */ new WeakMap();
1720
1744
  _log = /* @__PURE__ */ new WeakMap();
1721
1745
  _emit = /* @__PURE__ */ new WeakMap();
1722
1746
  _heartbeat = /* @__PURE__ */ new WeakMap();
1747
+ _identifierType = /* @__PURE__ */ new WeakMap();
1723
1748
  _onResponse = /* @__PURE__ */ new WeakMap();
1724
1749
  _stopHeartbeat = /* @__PURE__ */ new WeakMap();
1725
1750
  var _pending;
1726
1751
  var _onMutation;
1727
1752
  var _observer;
1753
+ var _root2;
1728
1754
  var _DomWatcher_instances;
1729
1755
  var ensureObserving_fn;
1730
1756
  var DomWatcher = class {
1731
- constructor() {
1757
+ constructor(root = document) {
1732
1758
  __privateAdd4(this, _DomWatcher_instances);
1733
1759
  __privateAdd4(this, _pending, /* @__PURE__ */ new Map());
1734
1760
  __privateAdd4(this, _onMutation, []);
1735
1761
  __privateAdd4(this, _observer, null);
1762
+ __privateAdd4(this, _root2);
1763
+ __privateSet4(this, _root2, root);
1764
+ }
1765
+ /** The first match in this watcher's root, if it is there now. */
1766
+ find(selector) {
1767
+ return __privateGet4(this, _root2).querySelector(selector);
1736
1768
  }
1737
1769
  /** Run `cb` with the first match now, or once the host renders one. */
1738
1770
  once(selector, cb) {
1739
- const now = document.querySelector(selector);
1771
+ const now = this.find(selector);
1740
1772
  if (now) {
1741
1773
  cb(now);
1742
1774
  return;
@@ -1761,12 +1793,13 @@ var DomWatcher = class {
1761
1793
  _pending = /* @__PURE__ */ new WeakMap();
1762
1794
  _onMutation = /* @__PURE__ */ new WeakMap();
1763
1795
  _observer = /* @__PURE__ */ new WeakMap();
1796
+ _root2 = /* @__PURE__ */ new WeakMap();
1764
1797
  _DomWatcher_instances = /* @__PURE__ */ new WeakSet();
1765
1798
  ensureObserving_fn = function() {
1766
1799
  if (__privateGet4(this, _observer)) return;
1767
1800
  __privateSet4(this, _observer, new MutationObserver(() => {
1768
1801
  for (const [selector, cbs] of [...__privateGet4(this, _pending)]) {
1769
- const found = document.querySelector(selector);
1802
+ const found = this.find(selector);
1770
1803
  if (!found) continue;
1771
1804
  __privateGet4(this, _pending).delete(selector);
1772
1805
  cbs.forEach((cb) => cb(found));
@@ -1774,7 +1807,8 @@ ensureObserving_fn = function() {
1774
1807
  __privateGet4(this, _onMutation).forEach((fn) => fn());
1775
1808
  if (!__privateGet4(this, _pending).size && !__privateGet4(this, _onMutation).length) this.stop();
1776
1809
  }));
1777
- __privateGet4(this, _observer).observe(document.body, { childList: true, subtree: true });
1810
+ const target = "body" in __privateGet4(this, _root2) ? __privateGet4(this, _root2).body : __privateGet4(this, _root2);
1811
+ __privateGet4(this, _observer).observe(target, { childList: true, subtree: true });
1778
1812
  };
1779
1813
  var keepPlaced = (dom, widget, target, position) => {
1780
1814
  const place = (anchor) => {
@@ -1784,7 +1818,7 @@ var keepPlaced = (dom, widget, target, position) => {
1784
1818
  place(anchor);
1785
1819
  dom.onEveryMutation(() => {
1786
1820
  if (widget.isConnected) return;
1787
- const a = document.querySelector(target);
1821
+ const a = dom.find(target);
1788
1822
  if (a) place(a);
1789
1823
  });
1790
1824
  });
@@ -1905,81 +1939,63 @@ var confirmationPage = {
1905
1939
  };
1906
1940
  var formPage = {
1907
1941
  heartbeat: true,
1942
+ identifierType: (config) => config.phoneInput ? "PHONE" : "EMAIL",
1908
1943
  validate(config) {
1909
1944
  if (!config.client) fail("client is required on the form page (build the SDK client with the form's adapter and pass it in)");
1910
- if (!config.emailInput) fail("emailInput is required on the form page");
1945
+ if (!config.emailInput && !config.phoneInput) fail("emailInput or phoneInput is required on the form page");
1946
+ if (config.emailInput && config.phoneInput) fail("pass either emailInput or phoneInput on the form page, not both (mount once per step)");
1911
1947
  },
1912
1948
  start({ config, client, log, emit, session, dom, onCleanup }) {
1913
- let emailUpdate = Promise.resolve();
1949
+ const phoneStep = !!config.phoneInput;
1950
+ let identifierUpdate = Promise.resolve();
1914
1951
  let submitted = false;
1915
- const watcher = new EmailWatcher({ onEmail: (email) => submitted ? Promise.resolve() : emailUpdate = session.upsert(email) });
1916
- dom.once(config.emailInput, (node) => watcher.attach(node));
1917
- onCleanup(() => watcher.stop());
1918
- const emailSettled = async () => {
1919
- await watcher.flush();
1920
- await emailUpdate;
1921
- };
1922
- let consented = false;
1923
- let consenting = null;
1924
- const consent = () => {
1925
- if (consented) return Promise.resolve();
1926
- consenting ?? (consenting = (async () => {
1927
- await emailSettled();
1928
- const saved = await session.saveConsent(true);
1929
- consented = saved;
1930
- emit("dataships:consent", { consent: true, saved });
1931
- consenting = null;
1932
- })());
1933
- return consenting;
1934
- };
1952
+ let watcher = null;
1953
+ if (config.emailInput) {
1954
+ const emailWatcher = new EmailWatcher({ onEmail: (email) => submitted ? Promise.resolve() : identifierUpdate = session.upsert(email) });
1955
+ watcher = emailWatcher;
1956
+ dom.once(config.emailInput, (node) => emailWatcher.attach(node));
1957
+ onCleanup(() => emailWatcher.stop());
1958
+ }
1935
1959
  let submitting = null;
1936
- const submit = () => {
1960
+ const submit = (input) => {
1937
1961
  submitting ?? (submitting = (async () => {
1938
- await consenting;
1939
- if (!consented) {
1940
- log("submit skipped: no consent has been saved");
1962
+ const refused = (error) => {
1963
+ log("submit failed", error);
1964
+ emit("dataships:submit", { ok: false, page: "form", error });
1941
1965
  submitting = null;
1942
- return;
1966
+ };
1967
+ await watcher?.flush();
1968
+ await identifierUpdate;
1969
+ const phone = input?.phone;
1970
+ if (phoneStep && !phone) return refused("no phone number was given");
1971
+ if (phone && phoneStep) {
1972
+ await (identifierUpdate = session.upsert(phone, { keepOnFailure: true }));
1973
+ if (!session.ok) return refused("the phone number could not be saved");
1943
1974
  }
1944
- await emailSettled();
1945
1975
  try {
1946
- await client.submitSession({ details: {} });
1976
+ await client.submitSession({ details: { identifierType: phoneStep ? "PHONE" : "EMAIL", ...config.submitDetails } });
1947
1977
  submitted = true;
1948
- watcher.stop();
1978
+ watcher?.stop();
1949
1979
  session.stop();
1950
1980
  log("submit ok", { page: "form" });
1951
1981
  emit("dataships:submit", { ok: true, page: "form" });
1952
1982
  } catch (e) {
1953
- const error = describeError(e);
1954
- log("submit failed", error);
1955
- emit("dataships:submit", { ok: false, page: "form", error });
1956
- submitting = null;
1983
+ refused(describeError(e));
1957
1984
  }
1958
1985
  })());
1959
1986
  return submitting;
1960
1987
  };
1961
- const submitIfConsented = () => {
1962
- if (consented || consenting) void submit();
1963
- };
1964
- const onVisibility = () => {
1965
- if (document.visibilityState === "hidden") submitIfConsented();
1966
- };
1967
- document.addEventListener("visibilitychange", onVisibility);
1968
- window.addEventListener("pagehide", submitIfConsented);
1969
- onCleanup(() => {
1970
- document.removeEventListener("visibilitychange", onVisibility);
1971
- window.removeEventListener("pagehide", submitIfConsented);
1972
- });
1973
1988
  const refresh = () => submitted ? Promise.resolve() : session.upsert(session.lastIdentifier);
1974
- return { ready: session.upsert(null), refresh, consent, submit };
1989
+ return { ready: session.upsert(null), refresh, submit };
1975
1990
  }
1976
1991
  };
1977
- var readInput = (selector) => selector ? (document.querySelector(selector)?.value ?? "").trim() : "";
1992
+ var readInput = (root, selector) => selector ? (root.querySelector(selector)?.value ?? "").trim() : "";
1978
1993
  var readSignupNames = (config) => {
1979
1994
  const fromResolver = config.user?.() ?? {};
1995
+ const root = config.root ?? document;
1980
1996
  return {
1981
- firstName: (fromResolver.firstName ?? readInput(config.firstNameInput)).trim(),
1982
- lastName: (fromResolver.lastName ?? readInput(config.lastNameInput)).trim()
1997
+ firstName: (fromResolver.firstName ?? readInput(root, config.firstNameInput)).trim(),
1998
+ lastName: (fromResolver.lastName ?? readInput(root, config.lastNameInput)).trim()
1983
1999
  };
1984
2000
  };
1985
2001
  var signupPage = {
@@ -2053,7 +2069,7 @@ var signupPage = {
2053
2069
  dom.once(config.emailInput, (node) => {
2054
2070
  watcher.attach(node);
2055
2071
  if ((config.submit ?? "form") !== "form") return;
2056
- const form = config.form ? document.querySelector(config.form) : node.closest("form");
2072
+ const form = config.form ? (config.root ?? document).querySelector(config.form) : node.closest("form");
2057
2073
  if (form) interceptForm(form);
2058
2074
  else log('signup form not found; native submit is not intercepted (use submit: "manual" and handle.submit())');
2059
2075
  });
@@ -2066,13 +2082,20 @@ var pages = {
2066
2082
  signup: signupPage,
2067
2083
  form: formPage
2068
2084
  };
2069
- var registry = /* @__PURE__ */ new Map();
2085
+ var registries = /* @__PURE__ */ new WeakMap();
2086
+ var registryFor = (root) => {
2087
+ let registry = registries.get(root);
2088
+ if (!registry) registries.set(root, registry = /* @__PURE__ */ new Map());
2089
+ return registry;
2090
+ };
2070
2091
  var validate = (config) => {
2071
2092
  if (!config || typeof config !== "object") fail("config object is required");
2072
2093
  if (!config.publicKey) fail("publicKey is required");
2073
2094
  if (!(config.page in pages)) fail('page must be "checkout", "confirmation", "signup" or "form"');
2074
2095
  if (!config.mount) fail("mount (CSS selector) is required");
2075
2096
  if (config.position !== void 0 && config.position !== "after" && config.position !== "before") fail('position must be "after" or "before"');
2097
+ if (config.className !== void 0 && typeof config.className !== "string") fail("className must be a string of class names separated by spaces");
2098
+ if (config.root !== void 0 && typeof config.root?.querySelector !== "function") fail("root must be a document or a shadow root");
2076
2099
  pages[config.page].validate(config);
2077
2100
  if (!config.client && !config.preview && !config.token && !config.unsafeServerKey) fail("token is required for live calls (the merchant server mints it); pass `preview: true` to style without credentials, or `client` to bring your own");
2078
2101
  if (config.token && config.unsafeServerKey) fail("pass either token or unsafeServerKey, not both");
@@ -2101,8 +2124,11 @@ var resolveClient = (config, log) => {
2101
2124
  var mount = (config) => {
2102
2125
  validate(config);
2103
2126
  defineWidget();
2104
- const { page, mount: target, appearance = {}, locale = "en", position = "after" } = config;
2127
+ const { page, appearance = {}, locale = "en", position = "after" } = config;
2128
+ const target = config.mount;
2105
2129
  const log = config.log ?? defaultLog;
2130
+ const root = config.root ?? document;
2131
+ const registry = registryFor(root);
2106
2132
  const existing = registry.get(target);
2107
2133
  if (existing) {
2108
2134
  existing.update({ appearance, page });
@@ -2110,14 +2136,21 @@ var mount = (config) => {
2110
2136
  }
2111
2137
  const client = resolveClient(config, log);
2112
2138
  const strategy = pages[page];
2139
+ const identifierType = strategy.identifierType?.(config) ?? "EMAIL";
2140
+ const channel = identifierType === "PHONE" ? "SMS" : "EMAIL";
2113
2141
  const widget = document.createElement(WIDGET_TAG);
2114
2142
  widget.setAttribute("data-page", page);
2115
2143
  widget.setAppearance(appearance);
2144
+ const classNames = config.className?.trim().split(/\s+/).filter(Boolean) ?? [];
2145
+ if (classNames.length) {
2146
+ widget.classList.add(...classNames);
2147
+ widget.setAttribute("data-host-styled", "");
2148
+ }
2116
2149
  const cleanups = [];
2117
2150
  const onCleanup = (fn) => {
2118
2151
  cleanups.push(fn);
2119
2152
  };
2120
- const dom = new DomWatcher();
2153
+ const dom = new DomWatcher(root);
2121
2154
  onCleanup(() => dom.stop());
2122
2155
  const emit = emitterFor(widget);
2123
2156
  const session = new Session({
@@ -2125,7 +2158,8 @@ var mount = (config) => {
2125
2158
  log,
2126
2159
  emit,
2127
2160
  heartbeat: strategy.heartbeat,
2128
- onResponse: (response) => widget.render(response, { page, locale })
2161
+ identifierType,
2162
+ onResponse: (response) => widget.render(response, { page, locale, channel })
2129
2163
  });
2130
2164
  widget.onConsentChange = (consent) => session.saveConsent(consent);
2131
2165
  keepPlaced(dom, widget, target, position);
@@ -2135,7 +2169,7 @@ var mount = (config) => {
2135
2169
  update: ({ appearance: a, page: p }) => {
2136
2170
  widget.setAppearance(a);
2137
2171
  if (p !== page) log("page change on a repeat mount() is not supported; unmount first");
2138
- widget.render(session.response, { page, locale });
2172
+ widget.render(session.response, { page, locale, channel });
2139
2173
  },
2140
2174
  handle: {
2141
2175
  ready,
@@ -2147,7 +2181,6 @@ var mount = (config) => {
2147
2181
  },
2148
2182
  refresh: run.refresh ?? (() => session.upsert(session.lastIdentifier)),
2149
2183
  ...run.submit ? { submit: run.submit } : {},
2150
- ...run.consent ? { consent: run.consent } : {},
2151
2184
  element: widget
2152
2185
  }
2153
2186
  };
@@ -2163,7 +2196,6 @@ var __accessCheck5 = (obj, member, msg) => member.has(obj) || __typeError5("Cann
2163
2196
  var __privateGet5 = (obj, member, getter) => (__accessCheck5(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
2164
2197
  var __privateAdd5 = (obj, member, value) => member.has(obj) ? __typeError5("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2165
2198
  var __privateSet5 = (obj, member, value, setter) => (__accessCheck5(obj, member, "write to private field"), member.set(obj, value), value);
2166
- var __privateMethod5 = (obj, member, method) => (__accessCheck5(obj, member, "access private method"), method);
2167
2199
  var DEFAULT_EMAIL_OPT_IN_TEXT3 = "We would like to email you news and promotions. Tick to opt in.";
2168
2200
  var DEFAULT_EMAIL_OPT_IN_CONSENT_DESCRIPTION3 = "Click here for an overview of how your personal data is processed for marketing purposes or see our Privacy Policy for further information.";
2169
2201
  var DEFAULT_SMS_OPT_IN_TEXT3 = "We would like to text you news and promotions. Tick to opt in.";
@@ -2259,111 +2291,6 @@ var previewUpsertResponse3 = (identifierType, format = "json") => {
2259
2291
  const response = identifierType === "PHONE" ? fakePhoneUpsertResponse3 : fakeEmailUpsertResponse3;
2260
2292
  return format === "html" ? withHtmlCopy3(response) : response;
2261
2293
  };
2262
- var randomUuid3 = (cryptoObj = globalThis.crypto) => {
2263
- if (cryptoObj && typeof cryptoObj.randomUUID === "function") {
2264
- return cryptoObj.randomUUID();
2265
- }
2266
- const bytes = new Uint8Array(16);
2267
- if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
2268
- cryptoObj.getRandomValues(bytes);
2269
- } else {
2270
- for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
2271
- }
2272
- bytes[6] = bytes[6] & 15 | 64;
2273
- bytes[8] = bytes[8] & 63 | 128;
2274
- const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
2275
- return hex.slice(0, 4).join("") + "-" + hex.slice(4, 6).join("") + "-" + hex.slice(6, 8).join("") + "-" + hex.slice(8, 10).join("") + "-" + hex.slice(10, 16).join("");
2276
- };
2277
- var DATASHIPS_SESSION_ID_MAX_LENGTH3 = 100;
2278
- var _explicitId3;
2279
- var _storageKey3;
2280
- var _window3;
2281
- var _id3;
2282
- var _SessionBeacon_instances3;
2283
- var safeStorage_fn3;
2284
- var SessionBeacon3 = class {
2285
- constructor(opts) {
2286
- __privateAdd5(this, _SessionBeacon_instances3);
2287
- __privateAdd5(this, _explicitId3);
2288
- __privateAdd5(this, _storageKey3);
2289
- __privateAdd5(this, _window3);
2290
- __privateAdd5(this, _id3, null);
2291
- if (opts.explicitId != null) assertSessionId3(opts.explicitId);
2292
- __privateSet5(this, _explicitId3, opts.explicitId ?? null);
2293
- __privateSet5(this, _storageKey3, opts.storageKey);
2294
- __privateSet5(this, _window3, opts.window ?? globalThis.window);
2295
- }
2296
- /**
2297
- * The beacon for this page. On first use a stored id is reused when
2298
- * `reusable(stored)` says so, otherwise a fresh UUID is minted; the record is
2299
- * rewritten with `step` every time so the next page knows where it was last
2300
- * used. Later calls return the same id for the adapter's lifetime.
2301
- */
2302
- resolve(step, reusable) {
2303
- if (__privateGet5(this, _explicitId3)) return __privateGet5(this, _explicitId3);
2304
- const storage = __privateMethod5(this, _SessionBeacon_instances3, safeStorage_fn3).call(this);
2305
- if (null === __privateGet5(this, _id3)) {
2306
- const stored = storage ? readStored3(storage, __privateGet5(this, _storageKey3)) : null;
2307
- __privateSet5(this, _id3, stored && reusable(stored) ? stored.id : randomUuid3(__privateGet5(this, _window3)?.crypto));
2308
- }
2309
- if (storage) {
2310
- try {
2311
- storage.setItem(__privateGet5(this, _storageKey3), JSON.stringify({ id: __privateGet5(this, _id3), lastStep: step }));
2312
- } catch {
2313
- }
2314
- }
2315
- return __privateGet5(this, _id3);
2316
- }
2317
- /** Discard the beacon so the next {@link resolve} mints a fresh one. No-op for an integrator-owned id. */
2318
- reset() {
2319
- if (__privateGet5(this, _explicitId3)) return;
2320
- __privateSet5(this, _id3, null);
2321
- const storage = __privateMethod5(this, _SessionBeacon_instances3, safeStorage_fn3).call(this);
2322
- if (!storage) return;
2323
- try {
2324
- storage.removeItem(__privateGet5(this, _storageKey3));
2325
- } catch {
2326
- }
2327
- }
2328
- };
2329
- _explicitId3 = /* @__PURE__ */ new WeakMap();
2330
- _storageKey3 = /* @__PURE__ */ new WeakMap();
2331
- _window3 = /* @__PURE__ */ new WeakMap();
2332
- _id3 = /* @__PURE__ */ new WeakMap();
2333
- _SessionBeacon_instances3 = /* @__PURE__ */ new WeakSet();
2334
- safeStorage_fn3 = function() {
2335
- try {
2336
- return __privateGet5(this, _window3)?.localStorage ?? null;
2337
- } catch {
2338
- return null;
2339
- }
2340
- };
2341
- var assertSessionId3 = (id) => {
2342
- if (typeof id !== "string" || id.length === 0) {
2343
- throw new Error("datashipsSessionId must be a non-empty string");
2344
- }
2345
- if (id.length > DATASHIPS_SESSION_ID_MAX_LENGTH3) {
2346
- throw new Error(
2347
- `datashipsSessionId must be at most ${DATASHIPS_SESSION_ID_MAX_LENGTH3} characters`
2348
- );
2349
- }
2350
- };
2351
- var readStored3 = (storage, key) => {
2352
- let raw;
2353
- try {
2354
- raw = storage.getItem(key);
2355
- } catch {
2356
- return null;
2357
- }
2358
- if (!raw) return null;
2359
- try {
2360
- const parsed = JSON.parse(raw);
2361
- if (typeof parsed?.id !== "string" || parsed.id.length === 0) return null;
2362
- return { id: parsed.id, lastStep: typeof parsed.lastStep === "string" ? parsed.lastStep : null };
2363
- } catch {
2364
- return null;
2365
- }
2366
- };
2367
2294
  var SUPPORTED_LOCALES3 = [
2368
2295
  "en",
2369
2296
  "es",
@@ -2392,33 +2319,21 @@ var coerceLocale3 = (raw) => {
2392
2319
  const head = raw.split(/[_-]/)[0]?.toLowerCase() ?? "";
2393
2320
  return SUPPORTED_LOCALES3.includes(head) ? head : "en";
2394
2321
  };
2395
- var ALIA_FORM_INTEGRATION_TYPE = "ALIA_FORM";
2396
- var STORAGE_KEY_PREFIX3 = "datashipsAliaSessionId:";
2322
+ var ALIA_FORM_RENDER_INTEGRATION_TYPE = "ALIA_FORM_RENDER";
2323
+ var ALIA_FORM_LISTEN_INTEGRATION_TYPE = "ALIA_FORM_LISTEN";
2324
+ var _datashipsSessionId;
2397
2325
  var _campaignId;
2398
2326
  var _locale3;
2399
- var _beacon3;
2400
- var AliaFormAdapter = class {
2401
- constructor(opts) {
2402
- this.name = "AliaFormAdapter";
2327
+ var AliaFormAdapterBase = class {
2328
+ constructor(adapterName, opts) {
2403
2329
  this.sessionApi = "consent-session";
2404
- this.integrationType = ALIA_FORM_INTEGRATION_TYPE;
2405
2330
  this.submitRequiresUser = false;
2331
+ __privateAdd5(this, _datashipsSessionId);
2406
2332
  __privateAdd5(this, _campaignId);
2407
2333
  __privateAdd5(this, _locale3);
2408
- __privateAdd5(this, _beacon3);
2409
- __privateSet5(this, _campaignId, required(opts.campaignId, "campaignId"));
2410
- const popupId = required(opts.popupId, "popupId");
2411
- const storageScope = required(opts.storageScope, "storageScope");
2334
+ __privateSet5(this, _datashipsSessionId, required(adapterName, opts.datashipsSessionId, "datashipsSessionId"));
2335
+ __privateSet5(this, _campaignId, required(adapterName, opts.campaignId, "campaignId"));
2412
2336
  __privateSet5(this, _locale3, coerceLocale3(opts.locale));
2413
- __privateSet5(this, _beacon3, new SessionBeacon3({
2414
- storageKey: `${STORAGE_KEY_PREFIX3}${storageScope}:${popupId}`,
2415
- window: opts.window
2416
- }));
2417
- this.previewMode = opts.previewMode ?? false;
2418
- }
2419
- /** Synthetic upsert response served in {@link previewMode}, matching the requested identifier type. */
2420
- getPreviewUpsertResponse(identifierType = "EMAIL") {
2421
- return previewUpsertResponse3(identifierType);
2422
2337
  }
2423
2338
  getLocale() {
2424
2339
  return __privateGet5(this, _locale3);
@@ -2431,31 +2346,75 @@ var AliaFormAdapter = class {
2431
2346
  getIdentifier(identifierType) {
2432
2347
  return { identifier: null, identifierType };
2433
2348
  }
2434
- /** The beacon this popup display is known by; resolved (and persisted) on first use. */
2349
+ /** The id the adapter was given; a submit leaves it in place. */
2435
2350
  getDatashipsSessionId() {
2436
- return __privateGet5(this, _beacon3).resolve(null, () => true);
2351
+ return __privateGet5(this, _datashipsSessionId);
2437
2352
  }
2438
- /** Discard the current beacon so the next call mints a fresh one, e.g. on every `alia:popupView`. */
2439
- resetDatashipsSessionId() {
2440
- __privateGet5(this, _beacon3).reset();
2441
- }
2442
- async getSessionContext() {
2443
- return { datashipsSessionId: this.getDatashipsSessionId(), campaignId: __privateGet5(this, _campaignId) };
2353
+ baseSessionContext() {
2354
+ return { datashipsSessionId: __privateGet5(this, _datashipsSessionId), campaignId: __privateGet5(this, _campaignId) };
2444
2355
  }
2445
2356
  };
2357
+ _datashipsSessionId = /* @__PURE__ */ new WeakMap();
2446
2358
  _campaignId = /* @__PURE__ */ new WeakMap();
2447
2359
  _locale3 = /* @__PURE__ */ new WeakMap();
2448
- _beacon3 = /* @__PURE__ */ new WeakMap();
2449
- var required = (value, option) => {
2360
+ var AliaFormRenderAdapter = class extends AliaFormAdapterBase {
2361
+ constructor(opts) {
2362
+ super("AliaFormRenderAdapter", opts);
2363
+ this.name = "AliaFormRenderAdapter";
2364
+ this.integrationType = ALIA_FORM_RENDER_INTEGRATION_TYPE;
2365
+ this.previewMode = opts.previewMode ?? false;
2366
+ }
2367
+ /** Synthetic upsert response served in {@link previewMode}, matching the requested identifier type. */
2368
+ getPreviewUpsertResponse(identifierType = "EMAIL") {
2369
+ return previewUpsertResponse3(identifierType);
2370
+ }
2371
+ async getSessionContext() {
2372
+ return this.baseSessionContext();
2373
+ }
2374
+ };
2375
+ var _disclosureText;
2376
+ var _privacyPolicyUrl;
2377
+ var _termsUrl;
2378
+ var AliaFormListenAdapter = class extends AliaFormAdapterBase {
2379
+ constructor(opts) {
2380
+ super("AliaFormListenAdapter", opts);
2381
+ this.name = "AliaFormListenAdapter";
2382
+ this.integrationType = ALIA_FORM_LISTEN_INTEGRATION_TYPE;
2383
+ __privateAdd5(this, _disclosureText);
2384
+ __privateAdd5(this, _privacyPolicyUrl);
2385
+ __privateAdd5(this, _termsUrl);
2386
+ __privateSet5(this, _disclosureText, optional(opts.disclosureText));
2387
+ __privateSet5(this, _privacyPolicyUrl, optional(opts.privacyPolicyUrl));
2388
+ __privateSet5(this, _termsUrl, optional(opts.termsUrl));
2389
+ }
2390
+ async getSessionContext() {
2391
+ return {
2392
+ ...this.baseSessionContext(),
2393
+ ...__privateGet5(this, _disclosureText) === void 0 ? {} : { disclosureText: __privateGet5(this, _disclosureText) },
2394
+ ...__privateGet5(this, _privacyPolicyUrl) === void 0 ? {} : { privacyPolicyUrl: __privateGet5(this, _privacyPolicyUrl) },
2395
+ ...__privateGet5(this, _termsUrl) === void 0 ? {} : { termsUrl: __privateGet5(this, _termsUrl) }
2396
+ };
2397
+ }
2398
+ };
2399
+ _disclosureText = /* @__PURE__ */ new WeakMap();
2400
+ _privacyPolicyUrl = /* @__PURE__ */ new WeakMap();
2401
+ _termsUrl = /* @__PURE__ */ new WeakMap();
2402
+ var required = (adapterName, value, option) => {
2450
2403
  if (typeof value !== "string" || value.trim().length === 0) {
2451
- throw new Error(`AliaFormAdapter: ${option} must be a non-empty string`);
2404
+ throw new Error(`${adapterName}: ${option} must be a non-empty string`);
2452
2405
  }
2453
2406
  return value;
2454
2407
  };
2408
+ var optional = (value) => typeof value === "string" && value.trim().length > 0 ? value : void 0;
2455
2409
 
2456
2410
  // src/modules/alia/template.ts
2457
2411
  var EMAIL_CONSENT = /\{\{\s*email_consent\s*\}\}/;
2412
+ var SMS_CONSENT = /\{\{\s*sms_consent\s*\}\}/;
2458
2413
  var ANY_CONSENT = /\{\{\s*\w+_consent\s*\}\}/;
2414
+ var hasOwnWording = (markdown) => {
2415
+ const rest = markdown.replace(new RegExp(EMAIL_CONSENT, "g"), "");
2416
+ return rest.trim() !== "" && !ANY_CONSENT.test(rest);
2417
+ };
2459
2418
  var FIBER_KEY_PREFIX = "__reactFiber$";
2460
2419
  var MAX_HOPS = 60;
2461
2420
  var MAX_DEPTH = 40;
@@ -2488,13 +2447,13 @@ var readSteps = (root) => {
2488
2447
  }
2489
2448
  return null;
2490
2449
  };
2491
- var findPlaceholderId = (steps) => {
2450
+ var findPlaceholderId = (steps, placeholder) => {
2492
2451
  let visited = 0;
2493
2452
  const search = (entry, depth) => {
2494
2453
  if (!isBag(entry) || depth > MAX_DEPTH || ++visited > MAX_NODES)
2495
2454
  return null;
2496
2455
  const { node, id, children } = entry;
2497
- if (isBag(node) && typeof node.markdown === "string" && EMAIL_CONSENT.test(node.markdown) && typeof id === "string" && SAFE_ID.test(id))
2456
+ if (isBag(node) && typeof node.markdown === "string" && placeholder.test(node.markdown) && typeof id === "string" && SAFE_ID.test(id))
2498
2457
  return id;
2499
2458
  if (!Array.isArray(children)) return null;
2500
2459
  for (const child of children) {
@@ -2509,14 +2468,14 @@ var findPlaceholderId = (steps) => {
2509
2468
  }
2510
2469
  return null;
2511
2470
  };
2512
- var findOwnText = (steps) => {
2471
+ var findOwnText = (steps, inputType) => {
2513
2472
  let visited = 0;
2514
2473
  const walk = (entry, depth, found) => {
2515
2474
  if (!isBag(entry) || depth > MAX_DEPTH || ++visited > MAX_NODES) return;
2516
2475
  const { node, id, children } = entry;
2517
2476
  if (isBag(node)) {
2518
- if (node.type === "emailInput") found.email = true;
2519
- if (node.sharedStyle === COMPLIANCE_STYLE && typeof node.markdown === "string" && node.markdown.trim() !== "" && !ANY_CONSENT.test(node.markdown) && typeof id === "string" && SAFE_ID.test(id))
2477
+ if (node.type === inputType) found.input = true;
2478
+ if (node.sharedStyle === COMPLIANCE_STYLE && typeof node.markdown === "string" && hasOwnWording(node.markdown) && typeof id === "string" && SAFE_ID.test(id))
2520
2479
  found.ids.push(id);
2521
2480
  }
2522
2481
  if (Array.isArray(children))
@@ -2524,29 +2483,108 @@ var findOwnText = (steps) => {
2524
2483
  };
2525
2484
  const ids = [];
2526
2485
  for (const step of steps) {
2527
- const found = { email: false, ids: [] };
2486
+ const found = { input: false, ids: [] };
2528
2487
  walk(step, 0, found);
2529
- if (found.email) ids.push(...found.ids);
2488
+ if (found.input) ids.push(...found.ids);
2530
2489
  }
2531
2490
  return ids;
2532
2491
  };
2533
- var readEmailDisclosure = (root) => {
2492
+ var readDisclosure = (root, placeholder, inputType) => {
2534
2493
  try {
2535
2494
  const steps = readSteps(root);
2536
2495
  if (!steps) return { kind: "unreadable" };
2537
- const id = findPlaceholderId(steps);
2538
- const ownText = findOwnText(steps);
2496
+ const id = findPlaceholderId(steps, placeholder);
2497
+ const ownText = findOwnText(steps, inputType);
2539
2498
  return id ? { kind: "placeholder", id, ownText } : { kind: "none", ownText };
2540
2499
  } catch {
2541
2500
  return { kind: "unreadable" };
2542
2501
  }
2543
2502
  };
2503
+ var readEmailDisclosure = (root) => readDisclosure(root, EMAIL_CONSENT, "emailInput");
2504
+ var readSmsDisclosure = (root) => readDisclosure(root, SMS_CONSENT, "phoneInput");
2544
2505
 
2545
2506
  // src/modules/alia/popups.ts
2546
2507
  var ANCHOR_ATTRIBUTE = "data-dataships-anchor";
2547
2508
  var STYLE_ATTRIBUTE = "data-dataships-launcher";
2509
+ var PENDING_ATTRIBUTE = "data-dataships-pending";
2510
+ var PENDING_LIMIT_MS = 3e4;
2511
+ var LOOK_ATTRIBUTE = "data-dataships-launcher-look";
2512
+ var FALLBACK_CLASS = "dataships-form-text";
2513
+ var COMPLIANCE_CLASS = "alia-style-compliance";
2514
+ var ALIA_STYLE_CLASS = /^alia-style-[\w-]+$/;
2515
+ var SCREEN_READER_ONLY = ".sr-only";
2516
+ var LOOK_PROPERTIES = [
2517
+ "color",
2518
+ "font-family",
2519
+ "font-size",
2520
+ "font-weight",
2521
+ "font-style",
2522
+ "line-height",
2523
+ "letter-spacing",
2524
+ "text-align",
2525
+ "text-transform",
2526
+ "opacity",
2527
+ "margin-top",
2528
+ "margin-bottom",
2529
+ "padding-top",
2530
+ "padding-right",
2531
+ "padding-bottom",
2532
+ "padding-left",
2533
+ "align-self"
2534
+ ];
2535
+ var UNSAFE_CSS_VALUE = /[{}<;]/;
2548
2536
  var SAFE_ID2 = /^[\w-]+$/;
2549
2537
  var EMAIL_INPUT = 'input[name="email"]';
2538
+ var PHONE_INPUT = 'input[name="phone"]';
2539
+ var lookOf = (source) => {
2540
+ const view = source.ownerDocument.defaultView;
2541
+ if (!view) return "";
2542
+ const computed = view.getComputedStyle(source);
2543
+ const value = (property) => {
2544
+ const found = computed.getPropertyValue(property).trim();
2545
+ return UNSAFE_CSS_VALUE.test(found) ? "" : found;
2546
+ };
2547
+ const declarations = [];
2548
+ for (const property of LOOK_PROPERTIES) {
2549
+ const found = value(property);
2550
+ if (found) declarations.push(`${property}:${found}`);
2551
+ }
2552
+ const left = value("margin-left");
2553
+ const right = value("margin-right");
2554
+ if (left && left === right && parseFloat(left) > 0)
2555
+ declarations.push("margin-left:auto", "margin-right:auto");
2556
+ else {
2557
+ if (left) declarations.push(`margin-left:${left}`);
2558
+ if (right) declarations.push(`margin-right:${right}`);
2559
+ }
2560
+ const width = source.getBoundingClientRect().width;
2561
+ if (width > 0)
2562
+ declarations.push(
2563
+ "box-sizing:border-box",
2564
+ `max-width:${Math.ceil(width)}px`
2565
+ );
2566
+ return declarations.join(";");
2567
+ };
2568
+ var classOf = (source) => Array.from(source.classList).filter((name) => ALIA_STYLE_CLASS.test(name)).join(" ") || FALLBACK_CLASS;
2569
+ var textOf = (elements) => elements.map((element) => {
2570
+ const copy = element.cloneNode(true);
2571
+ for (const hidden of Array.from(
2572
+ copy.querySelectorAll(SCREEN_READER_ONLY)
2573
+ ))
2574
+ hidden.remove();
2575
+ return (copy.textContent ?? "").replace(/\s+/g, " ").trim();
2576
+ }).filter((text) => text !== "").join(" ");
2577
+ var linkOf = (elements, kind) => {
2578
+ for (const element of elements)
2579
+ for (const link of Array.from(
2580
+ element.querySelectorAll("a[href]")
2581
+ )) {
2582
+ const href = link.href;
2583
+ if (!/^https?:\/\//i.test(href)) continue;
2584
+ if (kind.test(textOf([link])) || kind.test(href)) return href;
2585
+ }
2586
+ return void 0;
2587
+ };
2550
2588
  var idOf = (value) => {
2551
2589
  const id = typeof value === "number" || typeof value === "string" ? `${value}` : "";
2552
2590
  return SAFE_ID2.test(id) ? id : null;
@@ -2562,45 +2600,206 @@ var watchPopups = (context, deps) => {
2562
2600
  popup.observer = null;
2563
2601
  };
2564
2602
  const track = (popupId, campaignId) => {
2565
- const popup = { handle: null, observer: null, watched: null };
2603
+ const popup = {
2604
+ handle: null,
2605
+ emailSettled: false,
2606
+ sms: null,
2607
+ observer: null,
2608
+ watched: null
2609
+ };
2566
2610
  popups.set(popupId, popup);
2567
2611
  const buttonSelector = `[${ANCHOR_ATTRIBUTE}="${popupId}"]`;
2568
- const hideOwnText = (widget, ownText, shadow) => {
2612
+ const smsButtonMark = `${popupId}-sms`;
2613
+ const smsButtonSelector = `[${ANCHOR_ATTRIBUTE}="${smsButtonMark}"]`;
2614
+ const smsType = context.preview ? "SINGLE" : context.elements.find((element) => element.id === campaignId)?.channels.find((entry) => entry.channel === "SMS")?.subscriptionType;
2615
+ const popupRootOf = (shadow) => shadow ? '[id^="alia-popup-root-"]' : `#alia-root-${popupId}`;
2616
+ const inPopup = (selector, shadow) => shadow ? selector : `#alia-root-${popupId} ${selector}`;
2617
+ const renderClientOptions = () => ({
2618
+ campaignId,
2619
+ datashipsSessionId: context.datashipsSessionId,
2620
+ publicKey: context.publicKey,
2621
+ baseUrl: context.baseUrl,
2622
+ token: context.token,
2623
+ preview: context.preview
2624
+ });
2625
+ const hideOwnText = (handle, ownText, shadow) => {
2569
2626
  if (ownText.length === 0) return;
2570
- const popupRoot = shadow ? '[id^="alia-popup-root-"]' : `#alia-root-${popupId}`;
2627
+ const widget = handle.element;
2628
+ const popupRoot = popupRootOf(shadow);
2571
2629
  const shown = `${popupRoot}:has(${widget.localName}[data-visible])`;
2630
+ const pending = `${popupRoot}:has(${widget.localName}[${PENDING_ATTRIBUTE}])`;
2631
+ widget.setAttribute(PENDING_ATTRIBUTE, "");
2632
+ const settle = () => widget.removeAttribute(PENDING_ATTRIBUTE);
2633
+ const limit = setTimeout(settle, PENDING_LIMIT_MS);
2634
+ void handle.ready.then(() => {
2635
+ clearTimeout(limit);
2636
+ settle();
2637
+ });
2572
2638
  const style = document.createElement("style");
2573
2639
  style.setAttribute(STYLE_ATTRIBUTE, popupId);
2574
- style.textContent = ownText.map((id) => `${shown} #${id}{display:none!important}`).join("");
2640
+ style.textContent = ownText.map(
2641
+ (id) => `${pending} #${id}{visibility:hidden!important}${shown} #${id}{display:none!important}`
2642
+ ).join("");
2643
+ (shadow ?? document.head).appendChild(style);
2644
+ };
2645
+ const giveLook = (widget, mount2, look, shadow) => {
2646
+ if (!look) return;
2647
+ const style = document.createElement("style");
2648
+ style.setAttribute(LOOK_ATTRIBUTE, popupId);
2649
+ style.textContent = `${popupRootOf(shadow)} ${mount2} + ${widget.localName}{${look}}`;
2575
2650
  (shadow ?? document.head).appendChild(style);
2576
2651
  };
2577
- const mountAt = (mount2, ownText, shadow) => {
2652
+ const mountAt = (step, mount2, ownText, source, shadow) => {
2653
+ const look = source ? lookOf(source) : "";
2578
2654
  const handle = deps.mount({
2579
2655
  page: "form",
2580
2656
  publicKey: context.publicKey,
2581
- client: deps.createClient({
2582
- campaignId,
2583
- popupId,
2584
- publicKey: context.publicKey,
2585
- baseUrl: context.baseUrl,
2586
- token: context.token,
2587
- preview: context.preview
2588
- }),
2657
+ client: deps.createRenderClient(renderClientOptions()),
2589
2658
  mount: mount2,
2590
2659
  position: "after",
2591
- // Inside a shadow root the popup's own root is the host, out of a selector's reach.
2592
- emailInput: shadow ? EMAIL_INPUT : `#alia-root-${popupId} ${EMAIL_INPUT}`,
2660
+ ...step,
2661
+ className: source ? classOf(source) : COMPLIANCE_CLASS,
2593
2662
  ...shadow ? { root: shadow } : {},
2663
+ // The submit names the campaign, because one session id can hold several campaigns'
2664
+ // sessions, and the step's identifier type, so it completes this step's session only
2665
+ // and never contends with the other step's calls.
2666
+ submitDetails: {
2667
+ campaignId,
2668
+ identifierType: "emailInput" in step ? "EMAIL" : "PHONE"
2669
+ },
2594
2670
  log: () => {
2595
2671
  }
2596
2672
  });
2597
- popup.handle = handle;
2598
- hideOwnText(handle.element, ownText, shadow);
2673
+ hideOwnText(handle, ownText, shadow);
2674
+ giveLook(handle.element, mount2, look, shadow);
2675
+ return handle;
2599
2676
  };
2600
- const tagSubmitButton = (root) => {
2601
- const button = root.querySelector(EMAIL_INPUT)?.closest("form")?.querySelector('button[type="submit"]');
2602
- if (button && button.getAttribute(ANCHOR_ATTRIBUTE) !== popupId)
2603
- button.setAttribute(ANCHOR_ATTRIBUTE, popupId);
2677
+ const elementsOf = (root, ids) => ids.map((id) => root.querySelector(`#${id}`)).filter((element) => element !== null);
2678
+ const tagSubmitButton = (root, input, mark) => {
2679
+ const button = root.querySelector(input)?.closest("form")?.querySelector('button[type="submit"]') ?? null;
2680
+ if (button && button.getAttribute(ANCHOR_ATTRIBUTE) !== mark)
2681
+ button.setAttribute(ANCHOR_ATTRIBUTE, mark);
2682
+ return button;
2683
+ };
2684
+ const checkEmail = (root, shadow) => {
2685
+ if (popup.handle) {
2686
+ if (!popup.emailSettled) tagSubmitButton(root, EMAIL_INPUT, popupId);
2687
+ return;
2688
+ }
2689
+ const step = { emailInput: inPopup(EMAIL_INPUT, shadow) };
2690
+ const disclosure = readEmailDisclosure(root);
2691
+ if (disclosure.kind === "placeholder") {
2692
+ const [node] = elementsOf(root, [disclosure.id]);
2693
+ if (!node) return;
2694
+ popup.handle = mountAt(
2695
+ step,
2696
+ `#${disclosure.id}`,
2697
+ disclosure.ownText,
2698
+ node,
2699
+ shadow
2700
+ );
2701
+ popup.emailSettled = true;
2702
+ return;
2703
+ }
2704
+ if (disclosure.kind === "unreadable" && !root.querySelector(EMAIL_INPUT))
2705
+ return;
2706
+ const ownText = disclosure.kind === "none" ? disclosure.ownText : [];
2707
+ tagSubmitButton(root, EMAIL_INPUT, popupId);
2708
+ popup.handle = mountAt(
2709
+ step,
2710
+ buttonSelector,
2711
+ ownText,
2712
+ elementsOf(root, ownText)[0] ?? null,
2713
+ shadow
2714
+ );
2715
+ };
2716
+ const renderSms = (root, shadow) => {
2717
+ const disclosure = readSmsDisclosure(root);
2718
+ const step = { phoneInput: inPopup(PHONE_INPUT, shadow) };
2719
+ const ownText = disclosure.kind === "unreadable" ? [] : disclosure.ownText;
2720
+ const [node] = disclosure.kind === "placeholder" ? elementsOf(root, [disclosure.id]) : [];
2721
+ if (disclosure.kind === "placeholder" && node) {
2722
+ const handle2 = mountAt(
2723
+ step,
2724
+ `#${disclosure.id}`,
2725
+ [disclosure.id, ...ownText],
2726
+ node,
2727
+ shadow
2728
+ );
2729
+ popup.sms = { kind: "render", handle: handle2, retag: false };
2730
+ return;
2731
+ }
2732
+ if (!tagSubmitButton(root, PHONE_INPUT, smsButtonMark)) return;
2733
+ const handle = mountAt(
2734
+ step,
2735
+ smsButtonSelector,
2736
+ ownText,
2737
+ elementsOf(root, ownText)[0] ?? null,
2738
+ shadow
2739
+ );
2740
+ popup.sms = { kind: "render", handle, retag: true };
2741
+ };
2742
+ const listenSms = (root) => {
2743
+ const token = context.token;
2744
+ const datashipsSessionId = context.datashipsSessionId;
2745
+ const disclosure = readSmsDisclosure(root);
2746
+ const shown = disclosure.kind === "unreadable" ? [] : elementsOf(root, [
2747
+ ...disclosure.kind === "placeholder" ? [disclosure.id] : [],
2748
+ ...disclosure.ownText
2749
+ ]);
2750
+ const disclosureText = textOf(shown);
2751
+ if (disclosure.kind === "unreadable" || !token || !datashipsSessionId) {
2752
+ popup.sms = { kind: "none" };
2753
+ return;
2754
+ }
2755
+ const privacyPolicyUrl = linkOf(shown, /privacy/i);
2756
+ const termsUrl = linkOf(shown, /terms/i);
2757
+ const client = deps.createListenClient({
2758
+ campaignId,
2759
+ datashipsSessionId,
2760
+ publicKey: context.publicKey,
2761
+ baseUrl: context.baseUrl,
2762
+ token,
2763
+ ...disclosureText ? { disclosureText } : {},
2764
+ ...privacyPolicyUrl ? { privacyPolicyUrl } : {},
2765
+ ...termsUrl ? { termsUrl } : {}
2766
+ });
2767
+ let last = client.upsertSession({ identifierType: "PHONE" }).catch(() => {
2768
+ });
2769
+ let sent = false;
2770
+ popup.sms = {
2771
+ kind: "listen",
2772
+ send: (phone) => {
2773
+ if (sent) return;
2774
+ sent = true;
2775
+ last = last.then(
2776
+ () => client.upsertSession({
2777
+ identifierType: "PHONE",
2778
+ identifier: phone
2779
+ })
2780
+ ).then(
2781
+ () => client.submitSession({
2782
+ details: { campaignId, identifierType: "PHONE" }
2783
+ })
2784
+ ).catch(() => {
2785
+ sent = false;
2786
+ });
2787
+ }
2788
+ };
2789
+ };
2790
+ const checkSms = (root, shadow) => {
2791
+ if (popup.sms) {
2792
+ if (popup.sms.kind === "render" && popup.sms.retag)
2793
+ tagSubmitButton(root, PHONE_INPUT, smsButtonMark);
2794
+ return;
2795
+ }
2796
+ if (smsType !== "SINGLE" && smsType !== "DOUBLE") {
2797
+ popup.sms = { kind: "none" };
2798
+ return;
2799
+ }
2800
+ if (!root.querySelector(PHONE_INPUT)) return;
2801
+ if (smsType === "SINGLE") renderSms(root, shadow);
2802
+ else listenSms(root);
2604
2803
  };
2605
2804
  const check = () => {
2606
2805
  try {
@@ -2612,23 +2811,10 @@ var watchPopups = (context, deps) => {
2612
2811
  popup.watched = shadow;
2613
2812
  popup.observer?.observe(shadow, { childList: true, subtree: true });
2614
2813
  }
2615
- if (!popup.handle) {
2616
- const disclosure = readEmailDisclosure(root);
2617
- if (disclosure.kind === "placeholder") {
2618
- mountAt(`#${disclosure.id}`, disclosure.ownText, shadow);
2619
- return stopObserving(popup);
2620
- }
2621
- if (disclosure.kind === "unreadable" && !root.querySelector(EMAIL_INPUT))
2622
- return;
2623
- tagSubmitButton(root);
2624
- mountAt(
2625
- buttonSelector,
2626
- disclosure.kind === "none" ? disclosure.ownText : [],
2627
- shadow
2628
- );
2629
- return;
2630
- }
2631
- tagSubmitButton(root);
2814
+ checkEmail(root, shadow);
2815
+ checkSms(root, shadow);
2816
+ const smsDone = popup.sms !== null && !(popup.sms.kind === "render" && popup.sms.retag);
2817
+ if (popup.emailSettled && smsDone) stopObserving(popup);
2632
2818
  } catch {
2633
2819
  stopObserving(popup);
2634
2820
  }
@@ -2642,17 +2828,24 @@ var watchPopups = (context, deps) => {
2642
2828
  const campaignId = idOf(detail.campaignID);
2643
2829
  if (!popupId || !campaignId || popups.has(popupId)) return;
2644
2830
  if (!context.preview) {
2645
- if (!context.token || !context.campaignIds.includes(campaignId)) return;
2831
+ if (!context.token || !context.elements.some((element) => element.id === campaignId))
2832
+ return;
2646
2833
  }
2647
2834
  track(popupId, campaignId);
2648
2835
  };
2649
2836
  const onSignup = (detail) => {
2650
2837
  const popupId = idOf(detail.popupID);
2651
- const handle = popupId ? popups.get(popupId)?.handle : null;
2652
- if (!handle?.submit) return;
2653
- if (typeof detail.email !== "string" || detail.email === "") return;
2654
- void handle.submit().catch(() => {
2655
- });
2838
+ const popup = popupId ? popups.get(popupId) : void 0;
2839
+ if (!popup) return;
2840
+ if (typeof detail.email === "string" && detail.email !== "")
2841
+ void popup.handle?.submit?.().catch(() => {
2842
+ });
2843
+ const phone = detail.phone;
2844
+ if (typeof phone !== "string" || phone === "" || !popup.sms) return;
2845
+ if (popup.sms.kind === "render")
2846
+ void popup.sms.handle.submit?.({ phone }).catch(() => {
2847
+ });
2848
+ else if (popup.sms.kind === "listen") popup.sms.send(phone);
2656
2849
  };
2657
2850
  const onEvent = (event) => {
2658
2851
  try {
@@ -2673,24 +2866,36 @@ var watchPopups = (context, deps) => {
2673
2866
  };
2674
2867
 
2675
2868
  // src/modules/alia/index.ts
2676
- var createClient = (options) => {
2677
- const adapter = new AliaFormAdapter({
2869
+ var PREVIEW_SESSION_ID = "preview";
2870
+ var createRenderClient = (options) => {
2871
+ const adapter = new AliaFormRenderAdapter({
2872
+ datashipsSessionId: options.datashipsSessionId ?? PREVIEW_SESSION_ID,
2678
2873
  campaignId: options.campaignId,
2679
- popupId: options.popupId,
2680
- storageScope: options.publicKey,
2681
2874
  previewMode: options.preview
2682
2875
  });
2683
- adapter.resetDatashipsSessionId();
2684
2876
  return new DatashipsClient({
2685
2877
  adapter,
2686
2878
  app: "launcher",
2687
- version: "0.1.1",
2879
+ version: "0.2.0",
2688
2880
  baseUrl: options.baseUrl,
2689
2881
  ...options.token ? { auth: { publicKey: options.publicKey, token: options.token } } : {}
2690
2882
  });
2691
2883
  };
2884
+ var createListenClient = (options) => new DatashipsClient({
2885
+ adapter: new AliaFormListenAdapter({
2886
+ datashipsSessionId: options.datashipsSessionId,
2887
+ campaignId: options.campaignId,
2888
+ ...options.disclosureText ? { disclosureText: options.disclosureText } : {},
2889
+ ...options.privacyPolicyUrl ? { privacyPolicyUrl: options.privacyPolicyUrl } : {},
2890
+ ...options.termsUrl ? { termsUrl: options.termsUrl } : {}
2891
+ }),
2892
+ app: "launcher",
2893
+ version: "0.2.0",
2894
+ baseUrl: options.baseUrl,
2895
+ auth: { publicKey: options.publicKey, token: options.token }
2896
+ });
2692
2897
  var start = (context) => {
2693
- watchPopups(context, { mount, createClient });
2898
+ watchPopups(context, { mount, createRenderClient, createListenClient });
2694
2899
  };
2695
2900
 
2696
- export { createClient, start };
2901
+ export { createListenClient, createRenderClient, start };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dataships/launcher",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Dataships Launcher — the one storefront script. Reads the public key from its script tag, asks the Dataships API what to render and loads the matching module.",
5
5
  "private": false,
6
6
  "license": "Apache-2.0",
@@ -33,8 +33,8 @@
33
33
  "smoke:cdn": "node scripts/smoke-cdn.mjs"
34
34
  },
35
35
  "devDependencies": {
36
- "@dataships/elements": "2.1.0",
37
- "@dataships/sdk": "2.1.0",
36
+ "@dataships/elements": "2.5.0",
37
+ "@dataships/sdk": "2.4.0",
38
38
  "@types/node": "^20.12.11",
39
39
  "@typescript-eslint/eslint-plugin": "^7.0.0",
40
40
  "@typescript-eslint/parser": "^7.0.0",