veo-sdk 0.2.1 → 0.3.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,3 +1,4 @@
1
+ import { BUILDER_TOKEN_PARAM, BUILDER_ORIGIN_PARAM } from './chunk-JIU5JLI3.mjs';
1
2
  import { computePosition, offset, flip, shift, arrow } from '@floating-ui/dom';
2
3
 
3
4
  // src/utils/safe-env.ts
@@ -22,6 +23,66 @@ function hasNavigatorSendBeacon() {
22
23
  return typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function";
23
24
  }
24
25
 
26
+ // src/core/builder-token.ts
27
+ var TOKEN_KEY = "veo:builder_token";
28
+ var ORIGIN_KEY = "veo:builder_origin";
29
+ function session() {
30
+ try {
31
+ return window.sessionStorage;
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+ function urlParams() {
37
+ try {
38
+ return new URLSearchParams(window.location.search);
39
+ } catch {
40
+ return null;
41
+ }
42
+ }
43
+ function resolveBuilderToken() {
44
+ if (!hasWindow()) return null;
45
+ const params = urlParams();
46
+ const fromUrl = params?.get(BUILDER_TOKEN_PARAM);
47
+ if (fromUrl) {
48
+ const store = session();
49
+ try {
50
+ store?.setItem(TOKEN_KEY, fromUrl);
51
+ const origin = params?.get(BUILDER_ORIGIN_PARAM);
52
+ if (origin) store?.setItem(ORIGIN_KEY, origin);
53
+ } catch {
54
+ }
55
+ return fromUrl;
56
+ }
57
+ try {
58
+ return session()?.getItem(TOKEN_KEY) ?? null;
59
+ } catch {
60
+ return null;
61
+ }
62
+ }
63
+ function resolveBuilderOrigin() {
64
+ if (!hasWindow()) return null;
65
+ const fromUrl = urlParams()?.get(BUILDER_ORIGIN_PARAM);
66
+ if (fromUrl) return fromUrl;
67
+ try {
68
+ return session()?.getItem(ORIGIN_KEY) ?? null;
69
+ } catch {
70
+ return null;
71
+ }
72
+ }
73
+ function isBuilderMode() {
74
+ return resolveBuilderToken() !== null;
75
+ }
76
+ function clearBuilderToken() {
77
+ if (!hasWindow()) return;
78
+ try {
79
+ const store = session();
80
+ store?.removeItem(TOKEN_KEY);
81
+ store?.removeItem(ORIGIN_KEY);
82
+ } catch {
83
+ }
84
+ }
85
+
25
86
  // src/plugins/guides/constants.ts
26
87
  var GUIDE_Z_INDEX = 2147483640;
27
88
  var DEFAULT_ANCHOR_WAIT_MS = 5e3;
@@ -994,8 +1055,8 @@ function buildScale(wrapper, doc, min, max, btnClass, symbol) {
994
1055
  btn.addEventListener("click", () => {
995
1056
  selected = n;
996
1057
  buttons.forEach((b, i) => {
997
- const active2 = symbol ? i + min <= n : i + min === n;
998
- b.classList.toggle("veo-scale-active", active2);
1058
+ const active = symbol ? i + min <= n : i + min === n;
1059
+ b.classList.toggle("veo-scale-active", active);
999
1060
  });
1000
1061
  });
1001
1062
  buttons.push(btn);
@@ -1553,1043 +1614,6 @@ function safeDestroy(renderer) {
1553
1614
  }
1554
1615
  }
1555
1616
 
1556
- // src/plugins/plugin.ts
1557
- function definePlugin(plugin) {
1558
- return plugin;
1559
- }
1560
-
1561
- // src/plugins/guides/preview-mode.ts
1562
- var active = null;
1563
- async function runPreviewMode(opts) {
1564
- if (!hasDocument()) return null;
1565
- active?.teardown();
1566
- let guide = null;
1567
- try {
1568
- const res = await fetch(`${opts.apiUrl}/v1/guides/preview-resolve`, {
1569
- method: "POST",
1570
- headers: { "Content-Type": "application/json", "X-Api-Key": opts.apiKey },
1571
- body: JSON.stringify({ token: opts.token })
1572
- });
1573
- if (res.ok) {
1574
- const data = await res.json();
1575
- guide = data.guide ?? null;
1576
- } else if (opts.debug) {
1577
- console.warn("[veo] preview-resolve respondi\xF3", res.status);
1578
- }
1579
- } catch (err) {
1580
- if (opts.debug) console.warn("[veo] preview-resolve fall\xF3:", err);
1581
- }
1582
- const submitToBackend = async (answers) => {
1583
- if (!guide) return false;
1584
- const veo = window.veo;
1585
- const endUserId = veo?.getEndUserId?.() ?? veo?.getAnonymousId?.() ?? null;
1586
- if (!endUserId) return false;
1587
- try {
1588
- const res = await fetch(`${opts.apiUrl}/v1/guides/${guide.guideId}/form-response`, {
1589
- method: "POST",
1590
- headers: { "Content-Type": "application/json", "X-Api-Key": opts.apiKey },
1591
- body: JSON.stringify({ endUserId, answers })
1592
- });
1593
- return res.ok;
1594
- } catch {
1595
- return false;
1596
- }
1597
- };
1598
- let preview = null;
1599
- const show = () => {
1600
- if (!guide) return;
1601
- preview?.close();
1602
- preview = previewGuide({
1603
- guideType: guide.guideType,
1604
- guideSteps: guide.guideSteps,
1605
- activationRules: guide.activationRules,
1606
- guideName: guide.guideName,
1607
- formSubmit: submitToBackend,
1608
- formSubmitNote: "Vista previa: guardado en TU usuario para probar el flujo."
1609
- });
1610
- };
1611
- const chip = mountChip({
1612
- label: guide ? `Vista previa: ${guide.guideName}` : "Link de preview inv\xE1lido o vencido",
1613
- error: !guide,
1614
- onReshow: guide ? show : null,
1615
- onClose: () => handle.teardown()
1616
- });
1617
- const handle = {
1618
- teardown() {
1619
- preview?.close();
1620
- preview = null;
1621
- chip.remove();
1622
- if (active === handle) active = null;
1623
- }
1624
- };
1625
- active = handle;
1626
- show();
1627
- return handle;
1628
- }
1629
- function mountChip(opts) {
1630
- const host = document.createElement("div");
1631
- host.setAttribute("data-veo-preview-chip", "");
1632
- const root = host.attachShadow({ mode: "open" });
1633
- const style = document.createElement("style");
1634
- style.textContent = `
1635
- .chip { position: fixed; bottom: 16px; right: 16px; z-index: 2147483647;
1636
- display: flex; align-items: center; gap: 8px; padding: 8px 12px;
1637
- background: #111827; color: #f9fafb; border-radius: 9999px;
1638
- font: 500 12px/1.2 system-ui, sans-serif; box-shadow: 0 4px 12px rgba(0,0,0,.25); }
1639
- .chip.error { background: #7f1d1d; }
1640
- .label { max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1641
- button { all: unset; cursor: pointer; padding: 2px 6px; border-radius: 9999px;
1642
- font-size: 12px; line-height: 1; }
1643
- button:hover { background: rgba(255,255,255,.15); }
1644
- `;
1645
- root.appendChild(style);
1646
- const chip = document.createElement("div");
1647
- chip.className = opts.error ? "chip error" : "chip";
1648
- const label = document.createElement("span");
1649
- label.className = "label";
1650
- label.textContent = opts.label;
1651
- chip.appendChild(label);
1652
- if (opts.onReshow) {
1653
- const reshow = document.createElement("button");
1654
- reshow.textContent = "\u21BB";
1655
- reshow.title = "Volver a mostrar la gu\xEDa";
1656
- reshow.addEventListener("click", opts.onReshow);
1657
- chip.appendChild(reshow);
1658
- }
1659
- const close = document.createElement("button");
1660
- close.textContent = "\u2715";
1661
- close.title = "Salir de la vista previa";
1662
- close.addEventListener("click", opts.onClose);
1663
- chip.appendChild(close);
1664
- root.appendChild(chip);
1665
- document.body.appendChild(host);
1666
- return { remove: () => host.remove() };
1667
- }
1668
-
1669
- // src/plugins/guides/guide-frequency-cache.ts
1670
- var STATUS_PRIORITY = {
1671
- shown: 1,
1672
- dismissed: 2,
1673
- completed: 2
1674
- };
1675
- function namespaceFromApiKey(apiKey) {
1676
- return apiKey.slice(-16) || "default";
1677
- }
1678
- var GuideFrequencyCache = class {
1679
- constructor(namespace) {
1680
- this.storageKey = `${FREQUENCY_CACHE_KEY_PREFIX}${namespace}`;
1681
- this.cache = this.load();
1682
- this.prune();
1683
- }
1684
- /**
1685
- * Decide si una guía debe filtrarse localmente antes de pintarla.
1686
- *
1687
- * - `every_visit` / `always` → nunca filtra (siempre re-pinta).
1688
- * - `once` → cualquier entry registrada filtra (verla ya cuenta).
1689
- * - `until_dismissed` → si fue descartada O COMPLETADA (responder un
1690
- * form / terminar un walkthrough es más fuerte que descartar — sin
1691
- * esto, una encuesta seguiría preguntando después de respondida).
1692
- */
1693
- shouldFilter(guideId, displayFrequency) {
1694
- if (displayFrequency === "every_visit" || displayFrequency === "always") return false;
1695
- const entry = this.cache.get(guideId);
1696
- if (!entry) return false;
1697
- if (displayFrequency === "once") return true;
1698
- if (displayFrequency === "until_dismissed") {
1699
- return entry.status === "dismissed" || entry.status === "completed";
1700
- }
1701
- if (displayFrequency === "until_answered") return entry.status === "completed";
1702
- return false;
1703
- }
1704
- /**
1705
- * Registra/actualiza la entry de una guía. Nunca degrada un estado más
1706
- * fuerte (no convierte `dismissed` en `shown` por un re-render). Persiste
1707
- * cada llamada — escribir a localStorage es lo bastante barato.
1708
- */
1709
- record(guideId, status) {
1710
- const existing = this.cache.get(guideId);
1711
- if (existing && STATUS_PRIORITY[status] < STATUS_PRIORITY[existing.status]) {
1712
- return;
1713
- }
1714
- this.cache.set(guideId, {
1715
- guideId,
1716
- status,
1717
- lastInteractionAt: Date.now()
1718
- });
1719
- this.persist();
1720
- }
1721
- /** Limpia el cache (botón "reset" del demo, tests). */
1722
- clear() {
1723
- this.cache.clear();
1724
- this.persist();
1725
- }
1726
- /** Útil para debugging — devuelve un snapshot. */
1727
- snapshot() {
1728
- return Array.from(this.cache.values());
1729
- }
1730
- /**
1731
- * Limpia entries expiradas por TTL y, si aún excede el límite, descarta
1732
- * las más viejas hasta caber. Se ejecuta una vez en el constructor; no
1733
- * vale la pena correrlo a cada lectura.
1734
- */
1735
- prune() {
1736
- const now = Date.now();
1737
- let mutated = false;
1738
- for (const [id, entry] of this.cache) {
1739
- if (now - entry.lastInteractionAt > FREQUENCY_CACHE_TTL_MS) {
1740
- this.cache.delete(id);
1741
- mutated = true;
1742
- }
1743
- }
1744
- if (this.cache.size > FREQUENCY_CACHE_MAX_ENTRIES) {
1745
- const sorted = Array.from(this.cache.entries()).sort(
1746
- (a, b) => a[1].lastInteractionAt - b[1].lastInteractionAt
1747
- );
1748
- const excess = this.cache.size - FREQUENCY_CACHE_MAX_ENTRIES;
1749
- for (let i = 0; i < excess; i++) {
1750
- const tuple = sorted[i];
1751
- if (tuple) this.cache.delete(tuple[0]);
1752
- }
1753
- mutated = true;
1754
- }
1755
- if (mutated) this.persist();
1756
- }
1757
- load() {
1758
- if (typeof localStorage === "undefined") return /* @__PURE__ */ new Map();
1759
- try {
1760
- const raw = localStorage.getItem(this.storageKey);
1761
- if (!raw) return /* @__PURE__ */ new Map();
1762
- const parsed = JSON.parse(raw);
1763
- if (!Array.isArray(parsed)) return /* @__PURE__ */ new Map();
1764
- const entries = [];
1765
- for (const item of parsed) {
1766
- if (item && typeof item === "object" && typeof item.guideId === "string" && typeof item.lastInteractionAt === "number" && ["shown", "dismissed", "completed"].includes(item.status)) {
1767
- const e = item;
1768
- entries.push([e.guideId, e]);
1769
- }
1770
- }
1771
- return new Map(entries);
1772
- } catch {
1773
- return /* @__PURE__ */ new Map();
1774
- }
1775
- }
1776
- persist() {
1777
- if (typeof localStorage === "undefined") return;
1778
- try {
1779
- const serialized = JSON.stringify(Array.from(this.cache.values()));
1780
- localStorage.setItem(this.storageKey, serialized);
1781
- } catch {
1782
- }
1783
- }
1784
- };
1785
-
1786
- // src/plugins/guides/guide-resolver-client.ts
1787
- var GuideResolverClient = class {
1788
- constructor(apiUrl, apiKey, debug = false) {
1789
- this.apiUrl = apiUrl;
1790
- this.apiKey = apiKey;
1791
- this.debug = debug;
1792
- }
1793
- async resolve(endUserId, pageUrl) {
1794
- const params = new URLSearchParams({ endUserId, pageUrl });
1795
- let response;
1796
- try {
1797
- response = await fetch(`${this.apiUrl}/v1/guides/resolve?${params.toString()}`, {
1798
- method: "GET",
1799
- headers: { "X-Api-Key": this.apiKey },
1800
- credentials: "omit"
1801
- });
1802
- } catch (err) {
1803
- if (this.debug) console.error("[veo] guides resolve fetch failed:", err);
1804
- return [];
1805
- }
1806
- if (!response.ok) {
1807
- if (this.debug) console.warn("[veo] guides resolve HTTP", response.status);
1808
- return [];
1809
- }
1810
- try {
1811
- const data = await response.json();
1812
- return Array.isArray(data.guides) ? data.guides : [];
1813
- } catch (err) {
1814
- if (this.debug) console.error("[veo] guides resolve parse failed:", err);
1815
- return [];
1816
- }
1817
- }
1818
- /**
1819
- * Trae una guía específica por ID, sin pasar por la lógica de
1820
- * activación. La usa el controller para resumir un walkthrough entre
1821
- * páginas: el `resolve` no devuelve la guía si la URL actual no
1822
- * matchea, pero el walkthrough activo debe poder consultarla igual.
1823
- *
1824
- * El endpoint backend (`GET /v1/guides/:guideId`) devuelve `GuideResponse`,
1825
- * un superset de `ResolvedGuide` con campos de audit. Acá descartamos los
1826
- * extra y nos quedamos con el shape que el resto del SDK ya consume.
1827
- *
1828
- * Devuelve `null` en cualquier error (404, red, parse) — el caller debe
1829
- * tratarlo como "guía ya no existe" y cancelar el walkthrough limpiamente.
1830
- */
1831
- async fetchById(guideId) {
1832
- let response;
1833
- try {
1834
- response = await fetch(`${this.apiUrl}/v1/guides/${encodeURIComponent(guideId)}`, {
1835
- method: "GET",
1836
- headers: { "X-Api-Key": this.apiKey },
1837
- credentials: "omit"
1838
- });
1839
- } catch (err) {
1840
- if (this.debug) console.error("[veo] guides fetchById network failed:", err);
1841
- return null;
1842
- }
1843
- if (!response.ok) {
1844
- if (this.debug) console.warn("[veo] guides fetchById HTTP", response.status);
1845
- return null;
1846
- }
1847
- try {
1848
- const data = await response.json();
1849
- if (typeof data.guideId !== "string" || typeof data.guideName !== "string" || typeof data.guideType !== "string" || !Array.isArray(data.guideSteps) || !data.activationRules || typeof data.displayFrequency !== "string" || typeof data.displayPriority !== "number") {
1850
- if (this.debug) console.warn("[veo] guides fetchById: unexpected shape");
1851
- return null;
1852
- }
1853
- return {
1854
- guideId: data.guideId,
1855
- guideName: data.guideName,
1856
- guideType: data.guideType,
1857
- guideSteps: data.guideSteps,
1858
- activationRules: data.activationRules,
1859
- displayFrequency: data.displayFrequency,
1860
- displayPriority: data.displayPriority
1861
- };
1862
- } catch (err) {
1863
- if (this.debug) console.error("[veo] guides fetchById parse failed:", err);
1864
- return null;
1865
- }
1866
- }
1867
- };
1868
-
1869
- // src/plugins/guides/guide-tracker-client.ts
1870
- function toWire(payload) {
1871
- const wire = {
1872
- endUserId: payload.endUserId,
1873
- interactionType: payload.action
1874
- };
1875
- if (payload.sessionId) wire.sessionId = payload.sessionId;
1876
- if (typeof payload.stepIndex === "number") wire.stepPosition = payload.stepIndex;
1877
- if (payload.pageUrl) wire.pageUrl = payload.pageUrl;
1878
- if (payload.pagePath) wire.pagePath = payload.pagePath;
1879
- return wire;
1880
- }
1881
- var GuideTrackerClient = class {
1882
- constructor(apiUrl, apiKey) {
1883
- this.apiUrl = apiUrl;
1884
- this.apiKey = apiKey;
1885
- }
1886
- async send(request) {
1887
- const url = this.buildUrl(request.guideId);
1888
- const response = await fetch(url, {
1889
- method: "POST",
1890
- headers: {
1891
- "X-Api-Key": this.apiKey,
1892
- "Content-Type": "application/json"
1893
- },
1894
- body: JSON.stringify(toWire(request.payload)),
1895
- credentials: "omit"
1896
- });
1897
- if (!response.ok) {
1898
- throw new Error(`guide interaction send failed: HTTP ${response.status}`);
1899
- }
1900
- }
1901
- /**
1902
- * Envío "fire-and-forget" en pagehide. Devuelve `false` si el navegador
1903
- * no acepta el beacon (cola llena, no soportado) — en ese caso la queue
1904
- * sabrá que perdió el envío.
1905
- */
1906
- sendBeacon(request) {
1907
- if (typeof navigator === "undefined" || typeof navigator.sendBeacon !== "function") {
1908
- return false;
1909
- }
1910
- const url = `${this.buildUrl(request.guideId)}?key=${encodeURIComponent(this.apiKey)}`;
1911
- const blob = new Blob([JSON.stringify(toWire(request.payload))], {
1912
- type: "application/json"
1913
- });
1914
- try {
1915
- return navigator.sendBeacon(url, blob);
1916
- } catch {
1917
- return false;
1918
- }
1919
- }
1920
- buildUrl(guideId) {
1921
- return `${this.apiUrl}/v1/guides/${encodeURIComponent(guideId)}/interactions`;
1922
- }
1923
- };
1924
-
1925
- // src/plugins/guides/guide-tracker-queue.ts
1926
- var GuideTrackerQueue = class {
1927
- constructor(config) {
1928
- this.config = config;
1929
- this.buffer = [];
1930
- this.timer = null;
1931
- this.flushing = false;
1932
- this.unloadCleanup = null;
1933
- this.startTimer();
1934
- this.installUnloadHandler();
1935
- }
1936
- /** Tamaño actual del buffer (útil para debug/stats en el demo). */
1937
- get size() {
1938
- return this.buffer.length;
1939
- }
1940
- /**
1941
- * Encola una interaction. Si el buffer alcanza `batchSize`, dispara
1942
- * `flush()` inmediato.
1943
- */
1944
- enqueue(request) {
1945
- this.buffer.push({
1946
- guideId: request.guideId,
1947
- payload: request.payload,
1948
- attempts: 0,
1949
- enqueuedAt: Date.now()
1950
- });
1951
- if (this.buffer.length >= this.config.batchSize) {
1952
- void this.flush();
1953
- }
1954
- }
1955
- /**
1956
- * Envía todo el buffer en paralelo. Items que fallan vuelven al buffer
1957
- * si todavía tienen reintentos disponibles. Idempotente con respecto a
1958
- * flushes concurrentes (el segundo es un no-op).
1959
- */
1960
- async flush() {
1961
- if (this.flushing || this.buffer.length === 0) return;
1962
- this.flushing = true;
1963
- const batch = this.buffer.splice(0, this.buffer.length);
1964
- const results = await Promise.allSettled(
1965
- batch.map(
1966
- (item) => this.config.client.send({ guideId: item.guideId, payload: item.payload })
1967
- )
1968
- );
1969
- for (let i = 0; i < results.length; i++) {
1970
- const result = results[i];
1971
- const item = batch[i];
1972
- if (!result || !item) continue;
1973
- if (result.status === "fulfilled") continue;
1974
- item.attempts += 1;
1975
- if (item.attempts < this.config.maxRetries) {
1976
- this.buffer.push(item);
1977
- } else {
1978
- this.safeOnError(result.reason, item);
1979
- }
1980
- }
1981
- this.flushing = false;
1982
- }
1983
- /**
1984
- * Drena el buffer vía `sendBeacon`. Síncrono, sin retry. Para pagehide.
1985
- */
1986
- flushBeacon() {
1987
- if (this.buffer.length === 0) return;
1988
- const batch = this.buffer.splice(0, this.buffer.length);
1989
- for (const item of batch) {
1990
- this.config.client.sendBeacon({ guideId: item.guideId, payload: item.payload });
1991
- }
1992
- }
1993
- destroy() {
1994
- if (this.timer) clearInterval(this.timer);
1995
- this.timer = null;
1996
- this.unloadCleanup?.();
1997
- this.unloadCleanup = null;
1998
- }
1999
- startTimer() {
2000
- if (typeof window === "undefined") return;
2001
- this.timer = setInterval(() => {
2002
- void this.flush();
2003
- }, this.config.flushIntervalMs);
2004
- }
2005
- installUnloadHandler() {
2006
- if (typeof window === "undefined") return;
2007
- const onPagehide = () => this.flushBeacon();
2008
- const onVisibility = () => {
2009
- if (document.visibilityState === "hidden") this.flushBeacon();
2010
- };
2011
- window.addEventListener("pagehide", onPagehide);
2012
- window.addEventListener("visibilitychange", onVisibility);
2013
- this.unloadCleanup = () => {
2014
- window.removeEventListener("pagehide", onPagehide);
2015
- window.removeEventListener("visibilitychange", onVisibility);
2016
- };
2017
- }
2018
- safeOnError(reason, item) {
2019
- if (!this.config.onError) return;
2020
- const error = reason instanceof Error ? reason : new Error(String(reason));
2021
- try {
2022
- this.config.onError(error, item);
2023
- } catch {
2024
- }
2025
- }
2026
- };
2027
-
2028
- // src/plugins/guides/walkthrough-state.ts
2029
- var WalkthroughStateManager = class {
2030
- constructor(namespace) {
2031
- this.state = null;
2032
- this.storageKey = `${WALKTHROUGH_STATE_KEY_PREFIX}${namespace}`;
2033
- this.state = this.load();
2034
- if (this.state && this.isAbandoned(this.state)) {
2035
- this.clear();
2036
- }
2037
- }
2038
- /**
2039
- * Estado del walkthrough activo. Devuelve `null` si no hay ninguno o si
2040
- * el último progreso fue hace más del timeout (en ese caso también
2041
- * limpia el storage como side-effect).
2042
- */
2043
- current() {
2044
- if (!this.state) return null;
2045
- if (this.isAbandoned(this.state)) {
2046
- this.clear();
2047
- return null;
2048
- }
2049
- return this.state;
2050
- }
2051
- /** Atajo legible para el controller. */
2052
- hasActive() {
2053
- return this.current() !== null;
2054
- }
2055
- /**
2056
- * Inicia un nuevo walkthrough en step 0. Sobreescribe cualquier estado
2057
- * previo — los callers (controller) son responsables de verificar
2058
- * `hasActive()` antes si necesitan exclusividad.
2059
- */
2060
- start(guideId, totalSteps) {
2061
- const now = Date.now();
2062
- this.state = {
2063
- guideId,
2064
- totalSteps,
2065
- currentStepIndex: 0,
2066
- startedAt: now,
2067
- lastProgressAt: now
2068
- };
2069
- this.persist();
2070
- return this.state;
2071
- }
2072
- /**
2073
- * Avanza al siguiente step. Si el step resultante excede `totalSteps`,
2074
- * devuelve `null` y NO toca el estado — el controller debe interpretar
2075
- * eso como "ya estamos en el último, no hay próximo" y disparar
2076
- * `complete` vía el handler del botón "Finalizar".
2077
- */
2078
- advance() {
2079
- if (!this.state) return null;
2080
- const next = this.state.currentStepIndex + 1;
2081
- if (next >= this.state.totalSteps) return null;
2082
- this.state = {
2083
- ...this.state,
2084
- currentStepIndex: next,
2085
- lastProgressAt: Date.now()
2086
- };
2087
- this.persist();
2088
- return this.state;
2089
- }
2090
- /**
2091
- * Retrocede al step anterior. En step 0 no hace nada y devuelve el
2092
- * estado tal cual (el botón "Atrás" no debería estar visible en el
2093
- * primer step, pero por defensa el manager también lo guard-ea).
2094
- */
2095
- back() {
2096
- if (!this.state) return null;
2097
- if (this.state.currentStepIndex === 0) return this.state;
2098
- this.state = {
2099
- ...this.state,
2100
- currentStepIndex: this.state.currentStepIndex - 1,
2101
- lastProgressAt: Date.now()
2102
- };
2103
- this.persist();
2104
- return this.state;
2105
- }
2106
- /** Limpia el estado activo (skip, complete, abandono, guía borrada). */
2107
- clear() {
2108
- this.state = null;
2109
- if (typeof localStorage === "undefined") return;
2110
- try {
2111
- localStorage.removeItem(this.storageKey);
2112
- } catch {
2113
- }
2114
- }
2115
- isAbandoned(state) {
2116
- return Date.now() - state.lastProgressAt > WALKTHROUGH_ABANDONMENT_TIMEOUT_MS;
2117
- }
2118
- load() {
2119
- if (typeof localStorage === "undefined") return null;
2120
- try {
2121
- const raw = localStorage.getItem(this.storageKey);
2122
- if (!raw) return null;
2123
- const parsed = JSON.parse(raw);
2124
- if (!parsed || typeof parsed !== "object") return null;
2125
- const candidate = parsed;
2126
- if (typeof candidate.guideId !== "string" || typeof candidate.totalSteps !== "number" || typeof candidate.currentStepIndex !== "number" || typeof candidate.startedAt !== "number" || typeof candidate.lastProgressAt !== "number") {
2127
- return null;
2128
- }
2129
- return candidate;
2130
- } catch {
2131
- return null;
2132
- }
2133
- }
2134
- persist() {
2135
- if (typeof localStorage === "undefined" || !this.state) return;
2136
- try {
2137
- localStorage.setItem(this.storageKey, JSON.stringify(this.state));
2138
- } catch {
2139
- }
2140
- }
2141
- };
2142
-
2143
- // src/plugins/guides/guides-controller.ts
2144
- var STATUS_BY_ACTION = {
2145
- shown: "shown",
2146
- dismissed: "dismissed",
2147
- cta_clicked: null,
2148
- step_advanced: null,
2149
- step_back: null,
2150
- completed: "completed"
2151
- };
2152
- var GuidesController = class {
2153
- constructor(client, config) {
2154
- this.client = client;
2155
- this.activeRenderers = /* @__PURE__ */ new Set();
2156
- /**
2157
- * Guías single-step actualmente en pantalla, por `guideId`. Evita repintar/
2158
- * duplicar la misma guía en cada pageview de una SPA (p.ej. una guía inline
2159
- * anclada a un elemento persistente). Se libera al cerrarse la guía.
2160
- */
2161
- this.activeByGuideId = /* @__PURE__ */ new Map();
2162
- this.dispatched = /* @__PURE__ */ new Set();
2163
- this.activeWalkthroughRenderer = null;
2164
- this.activeWalkthroughGuide = null;
2165
- this.debug = config.debug === true;
2166
- this.apiUrl = config.apiUrl;
2167
- this.apiKey = config.apiKey;
2168
- this.resolver = config.resolver ?? new GuideResolverClient(config.apiUrl, config.apiKey, this.debug);
2169
- if (config.trackerQueue) {
2170
- this.trackerQueue = config.trackerQueue;
2171
- } else {
2172
- const httpClient = new GuideTrackerClient(config.apiUrl, config.apiKey);
2173
- this.trackerQueue = new GuideTrackerQueue({
2174
- client: httpClient,
2175
- flushIntervalMs: DEFAULT_TRACKER_FLUSH_INTERVAL_MS,
2176
- batchSize: DEFAULT_TRACKER_BATCH_SIZE,
2177
- maxRetries: DEFAULT_TRACKER_MAX_RETRIES,
2178
- onError: (err, item) => {
2179
- if (this.debug) {
2180
- console.warn(
2181
- `[veo] dropped guide interaction after retries: guideId=${item.guideId} action=${item.payload.action}`,
2182
- err
2183
- );
2184
- }
2185
- }
2186
- });
2187
- }
2188
- const namespace = namespaceFromApiKey(config.apiKey);
2189
- this.frequencyCache = config.frequencyCache ?? new GuideFrequencyCache(namespace);
2190
- this.walkthroughState = config.walkthroughState ?? new WalkthroughStateManager(namespace);
2191
- }
2192
- /** Cuántas interactions hay pendientes de envío. Útil para debug en demo. */
2193
- get pendingInteractions() {
2194
- return this.trackerQueue.size;
2195
- }
2196
- /** Limpia el cache local (botón "reset" del demo, tests). */
2197
- clearFrequencyCache() {
2198
- this.frequencyCache.clear();
2199
- }
2200
- /** Limpia el walkthrough activo (debug del demo). */
2201
- clearWalkthroughState() {
2202
- this.tearDownWalkthrough();
2203
- }
2204
- /** Punto de entrada principal. Llamado en cada pageview/identify. */
2205
- async checkGuides(pageUrl, sessionId) {
2206
- const endUserId = this.client.getEndUserId();
2207
- if (!endUserId) {
2208
- if (this.debug) console.log("[veo] guides: skipped, no endUserId yet");
2209
- return;
2210
- }
2211
- if (await this.tryResumeWalkthrough(endUserId, sessionId, pageUrl)) {
2212
- return;
2213
- }
2214
- let guides;
2215
- try {
2216
- guides = await this.resolver.resolve(endUserId, pageUrl);
2217
- } catch (err) {
2218
- if (this.debug) console.error("[veo] guides resolver threw:", err);
2219
- return;
2220
- }
2221
- if (this.debug) console.log(`[veo] guides: ${guides.length} eligible at ${pageUrl}`);
2222
- for (const guide of guides) {
2223
- if (this.frequencyCache.shouldFilter(guide.guideId, guide.displayFrequency)) {
2224
- if (this.debug) console.log(`[veo] guides: filtered locally guideId=${guide.guideId}`);
2225
- continue;
2226
- }
2227
- if (this.activeByGuideId.has(guide.guideId)) {
2228
- if (this.debug) console.log(`[veo] guides: already shown guideId=${guide.guideId}`);
2229
- continue;
2230
- }
2231
- if (guide.guideType === "walkthrough" && guide.guideSteps.length > 1) {
2232
- if (this.walkthroughState.hasActive()) {
2233
- if (this.debug)
2234
- console.log(`[veo] guides: walkthrough ${guide.guideId} skipped (another active)`);
2235
- continue;
2236
- }
2237
- await this.startWalkthrough(guide, endUserId, sessionId, pageUrl);
2238
- continue;
2239
- }
2240
- this.runSingleStepRender(guide, sessionId, pageUrl);
2241
- }
2242
- }
2243
- /** Cierra todas las guías activas, limpia cache de dispatch y para timers. */
2244
- destroy() {
2245
- for (const renderer of this.activeRenderers) {
2246
- try {
2247
- renderer.destroy();
2248
- } catch (err) {
2249
- if (this.debug) console.error("[veo] renderer destroy failed:", err);
2250
- }
2251
- }
2252
- this.activeRenderers.clear();
2253
- this.activeByGuideId.clear();
2254
- if (this.activeWalkthroughRenderer) {
2255
- try {
2256
- this.activeWalkthroughRenderer.destroy();
2257
- } catch {
2258
- }
2259
- this.activeWalkthroughRenderer = null;
2260
- this.activeWalkthroughGuide = null;
2261
- }
2262
- this.dispatched.clear();
2263
- this.trackerQueue.destroy();
2264
- }
2265
- runSingleStepRender(guide, sessionId, pageUrl) {
2266
- const renderer = this.createSingleStepRenderer(guide.guideType);
2267
- if (!renderer) return;
2268
- this.activeByGuideId.set(guide.guideId, renderer);
2269
- const delayMs = guide.activationRules.delayMs ?? 0;
2270
- window.setTimeout(
2271
- () => this.mountSingleStepRenderer(guide, renderer, sessionId, pageUrl),
2272
- delayMs
2273
- );
2274
- }
2275
- mountSingleStepRenderer(guide, renderer, sessionId, pageUrl) {
2276
- this.activeRenderers.add(renderer);
2277
- this.activeByGuideId.set(guide.guideId, renderer);
2278
- const onClose = () => {
2279
- renderer.destroy();
2280
- this.activeRenderers.delete(renderer);
2281
- if (this.activeByGuideId.get(guide.guideId) === renderer) {
2282
- this.activeByGuideId.delete(guide.guideId);
2283
- }
2284
- };
2285
- const onInteraction = (event) => {
2286
- this.handleInteraction(guide, sessionId, pageUrl, event);
2287
- };
2288
- const onTrack = (eventName, properties) => {
2289
- this.client.track(eventName, properties);
2290
- };
2291
- const onFormSubmit = (answers) => this.submitFormResponse(guide.guideId, answers);
2292
- try {
2293
- void renderer.render({ guide, onInteraction, onClose, onTrack, onFormSubmit });
2294
- } catch (err) {
2295
- if (this.debug) console.error("[veo] renderer.render threw:", err);
2296
- this.activeRenderers.delete(renderer);
2297
- if (this.activeByGuideId.get(guide.guideId) === renderer) {
2298
- this.activeByGuideId.delete(guide.guideId);
2299
- }
2300
- }
2301
- }
2302
- /**
2303
- * Si hay un walkthrough persistido, intenta pintar el step actual en
2304
- * la página actual. Retorna `true` si lo intentó (sea éxito o cancel),
2305
- * `false` si no había walkthrough activo.
2306
- *
2307
- * Cancela limpiamente (sin enviar `dismissed` falso) cuando:
2308
- * - La guía fue eliminada en el backend (404 → `fetchById` devuelve null).
2309
- * - La guía cambió de tipo y ya no es walkthrough.
2310
- * - El selector del step actual no aparece dentro del timeout.
2311
- */
2312
- async tryResumeWalkthrough(endUserId, sessionId, pageUrl) {
2313
- const state = this.walkthroughState.current();
2314
- if (!state) return false;
2315
- const guide = await this.resolver.fetchById(state.guideId);
2316
- if (!guide || guide.guideType !== "walkthrough") {
2317
- if (this.debug)
2318
- console.log(`[veo] guides: walkthrough ${state.guideId} no longer available, cleaning up`);
2319
- this.tearDownWalkthrough();
2320
- return true;
2321
- }
2322
- const stepIndex = Math.min(state.currentStepIndex, guide.guideSteps.length - 1);
2323
- await this.renderWalkthroughStep(guide, stepIndex, endUserId, sessionId, pageUrl);
2324
- return true;
2325
- }
2326
- async startWalkthrough(guide, endUserId, sessionId, pageUrl) {
2327
- this.walkthroughState.start(guide.guideId, guide.guideSteps.length);
2328
- const rendered = await this.renderWalkthroughStep(guide, 0, endUserId, sessionId, pageUrl);
2329
- if (!rendered) return;
2330
- this.enqueueInteractionOnce(guide.guideId, endUserId, sessionId, pageUrl, "shown", 0);
2331
- this.frequencyCache.record(guide.guideId, "shown");
2332
- }
2333
- /**
2334
- * Pinta el step indicado. Reusa la guía (no fetcha): el caller debe
2335
- * traerla. Retorna `true` si el render fue exitoso. En caso contrario
2336
- * ya disparó el teardown — el caller no debe seguir reportando.
2337
- */
2338
- async renderWalkthroughStep(guide, stepIndex, endUserId, sessionId, pageUrl) {
2339
- if (this.activeWalkthroughRenderer) {
2340
- this.activeWalkthroughRenderer.destroy();
2341
- this.activeWalkthroughRenderer = null;
2342
- }
2343
- const renderer = new WalkthroughRenderer();
2344
- this.activeWalkthroughGuide = guide;
2345
- const callbacks = {
2346
- onNext: () => this.handleWalkthroughNext(endUserId, sessionId, pageUrl),
2347
- onBack: () => this.handleWalkthroughBack(endUserId, sessionId, pageUrl),
2348
- onSkip: () => this.handleWalkthroughSkip(endUserId, sessionId, pageUrl),
2349
- onComplete: () => this.handleWalkthroughComplete(endUserId, sessionId, pageUrl)
2350
- };
2351
- let success = false;
2352
- try {
2353
- success = await renderer.render({ guide, currentStepIndex: stepIndex, callbacks });
2354
- } catch (err) {
2355
- if (this.debug) console.error("[veo] walkthrough renderer threw:", err);
2356
- }
2357
- if (!success) {
2358
- if (this.debug)
2359
- console.warn(
2360
- `[veo] walkthrough ${guide.guideId} step ${stepIndex} could not render, cancelling`
2361
- );
2362
- this.tearDownWalkthrough();
2363
- return false;
2364
- }
2365
- this.activeWalkthroughRenderer = renderer;
2366
- return true;
2367
- }
2368
- handleWalkthroughNext(endUserId, sessionId, pageUrl) {
2369
- const guide = this.activeWalkthroughGuide;
2370
- if (!guide) return;
2371
- const newState = this.walkthroughState.advance();
2372
- if (!newState) {
2373
- this.handleWalkthroughComplete(endUserId, sessionId, pageUrl);
2374
- return;
2375
- }
2376
- this.enqueueInteraction(
2377
- guide.guideId,
2378
- endUserId,
2379
- sessionId,
2380
- pageUrl,
2381
- "step_advanced",
2382
- newState.currentStepIndex
2383
- );
2384
- void this.renderWalkthroughStep(
2385
- guide,
2386
- newState.currentStepIndex,
2387
- endUserId,
2388
- sessionId,
2389
- pageUrl
2390
- );
2391
- }
2392
- handleWalkthroughBack(endUserId, sessionId, pageUrl) {
2393
- const guide = this.activeWalkthroughGuide;
2394
- if (!guide) return;
2395
- const state = this.walkthroughState.current();
2396
- if (!state || state.currentStepIndex === 0) return;
2397
- const newState = this.walkthroughState.back();
2398
- if (!newState) return;
2399
- this.enqueueInteraction(
2400
- guide.guideId,
2401
- endUserId,
2402
- sessionId,
2403
- pageUrl,
2404
- "step_back",
2405
- newState.currentStepIndex
2406
- );
2407
- void this.renderWalkthroughStep(
2408
- guide,
2409
- newState.currentStepIndex,
2410
- endUserId,
2411
- sessionId,
2412
- pageUrl
2413
- );
2414
- }
2415
- handleWalkthroughSkip(endUserId, sessionId, pageUrl) {
2416
- const guide = this.activeWalkthroughGuide;
2417
- const state = this.walkthroughState.current();
2418
- if (!guide || !state) return;
2419
- this.enqueueInteraction(
2420
- guide.guideId,
2421
- endUserId,
2422
- sessionId,
2423
- pageUrl,
2424
- "dismissed",
2425
- state.currentStepIndex
2426
- );
2427
- this.frequencyCache.record(guide.guideId, "dismissed");
2428
- this.tearDownWalkthrough();
2429
- }
2430
- handleWalkthroughComplete(endUserId, sessionId, pageUrl) {
2431
- const guide = this.activeWalkthroughGuide;
2432
- const state = this.walkthroughState.current();
2433
- if (!guide || !state) return;
2434
- this.enqueueInteraction(
2435
- guide.guideId,
2436
- endUserId,
2437
- sessionId,
2438
- pageUrl,
2439
- "completed",
2440
- state.currentStepIndex
2441
- );
2442
- this.frequencyCache.record(guide.guideId, "completed");
2443
- this.tearDownWalkthrough();
2444
- }
2445
- tearDownWalkthrough() {
2446
- if (this.activeWalkthroughRenderer) {
2447
- try {
2448
- this.activeWalkthroughRenderer.destroy();
2449
- } catch {
2450
- }
2451
- }
2452
- this.activeWalkthroughRenderer = null;
2453
- this.activeWalkthroughGuide = null;
2454
- this.walkthroughState.clear();
2455
- }
2456
- /**
2457
- * Tras cada interaction single-step:
2458
- * 1. dedupe (no enviar 2× la misma `(guideId, action)` por sesión)
2459
- * 2. actualizar el cache local si corresponde
2460
- * 3. encolar el POST
2461
- *
2462
- * El endUserId se lee del client EN ESTE MOMENTO (no en el render),
2463
- * por si el usuario se identificó después de que la guía apareció.
2464
- */
2465
- handleInteraction(guide, sessionId, pageUrl, event) {
2466
- const dedupKey = `${guide.guideId}:${event.action}`;
2467
- if (this.dispatched.has(dedupKey)) {
2468
- if (this.debug) console.log(`[veo] guides: dedup hit ${dedupKey}`);
2469
- return;
2470
- }
2471
- this.dispatched.add(dedupKey);
2472
- const cacheStatus = STATUS_BY_ACTION[event.action];
2473
- if (cacheStatus) this.frequencyCache.record(guide.guideId, cacheStatus);
2474
- const endUserId = this.client.getEndUserId();
2475
- if (!endUserId) {
2476
- if (this.debug)
2477
- console.warn("[veo] guides: interaction without endUserId \u2014 skipping enqueue");
2478
- return;
2479
- }
2480
- this.trackerQueue.enqueue({
2481
- guideId: guide.guideId,
2482
- payload: {
2483
- endUserId,
2484
- sessionId,
2485
- action: event.action,
2486
- stepIndex: event.stepIndex,
2487
- pageUrl,
2488
- pagePath: extractPath(pageUrl)
2489
- }
2490
- });
2491
- }
2492
- /**
2493
- * Encola una interacción de walkthrough SIN pasar por el dedup set.
2494
- * Acciones como `step_advanced` se repiten naturalmente (cada next es
2495
- * una navegación distinta) y deduplicarlas perdería datos.
2496
- */
2497
- enqueueInteraction(guideId, endUserId, sessionId, pageUrl, action, stepIndex) {
2498
- this.trackerQueue.enqueue({
2499
- guideId,
2500
- payload: {
2501
- endUserId,
2502
- sessionId,
2503
- action,
2504
- stepIndex,
2505
- pageUrl,
2506
- pagePath: extractPath(pageUrl)
2507
- }
2508
- });
2509
- }
2510
- /**
2511
- * Encola con dedup por sesión del SDK. Para `shown` del primer step:
2512
- * no queremos re-emitirlo si el usuario navega entre dos páginas que
2513
- * matchean el mismo step.
2514
- */
2515
- enqueueInteractionOnce(guideId, endUserId, sessionId, pageUrl, action, stepIndex) {
2516
- const dedupKey = `${guideId}:${action}:${stepIndex}`;
2517
- if (this.dispatched.has(dedupKey)) return;
2518
- this.dispatched.add(dedupKey);
2519
- this.enqueueInteraction(guideId, endUserId, sessionId, pageUrl, action, stepIndex);
2520
- }
2521
- createSingleStepRenderer(type) {
2522
- switch (type) {
2523
- case "modal":
2524
- return new ModalRenderer();
2525
- case "banner":
2526
- return new BannerRenderer();
2527
- case "tooltip":
2528
- return new TooltipRenderer();
2529
- case "custom":
2530
- return new CustomRenderer();
2531
- case "inline":
2532
- return new InlineRenderer();
2533
- case "inline-custom":
2534
- return new InlineCustomRenderer();
2535
- case "form":
2536
- return new FormRenderer();
2537
- case "inline-form":
2538
- return new InlineFormRenderer();
2539
- case "walkthrough":
2540
- return null;
2541
- }
2542
- }
2543
- /**
2544
- * Envía las respuestas de una guía `form` al backend, que las mergea como
2545
- * propiedades del usuario. Usa el endUserId actual (o el anónimo si aún no
2546
- * hubo identify — el backend pre-crea la fila igual que identify).
2547
- */
2548
- async submitFormResponse(guideId, answers) {
2549
- const endUserId = this.client.getEndUserId() ?? this.client.getAnonymousId();
2550
- try {
2551
- const res = await fetch(`${this.apiUrl}/v1/guides/${guideId}/form-response`, {
2552
- method: "POST",
2553
- headers: { "Content-Type": "application/json", "X-Api-Key": this.apiKey },
2554
- body: JSON.stringify({ endUserId, answers })
2555
- });
2556
- if (!res.ok && this.debug) {
2557
- console.warn("[veo] form-response respondi\xF3", res.status);
2558
- }
2559
- return res.ok;
2560
- } catch (err) {
2561
- if (this.debug) console.warn("[veo] form-response fall\xF3:", err);
2562
- return false;
2563
- }
2564
- }
2565
- };
2566
- function extractPath(url) {
2567
- try {
2568
- return new URL(url).pathname;
2569
- } catch {
2570
- return "/";
2571
- }
2572
- }
2573
-
2574
- // src/plugins/guides/index.ts
2575
- function guidesPlugin(config) {
2576
- return definePlugin({
2577
- name: "guides",
2578
- install(client) {
2579
- if (!hasWindow()) return;
2580
- const controller = new GuidesController(client, config);
2581
- window.__veoGuides = { controller };
2582
- client.on("identify", ({ sessionId }) => {
2583
- void controller.checkGuides(window.location.href, sessionId);
2584
- });
2585
- client.on("pageview", ({ url, sessionId }) => {
2586
- void controller.checkGuides(url, sessionId);
2587
- });
2588
- void controller.checkGuides(window.location.href, client.getSessionId());
2589
- }
2590
- });
2591
- }
2592
-
2593
1617
  // src/plugins/autocapture/constants.ts
2594
1618
  var DEFAULT_AUTOCAPTURE_CONFIG = {
2595
1619
  enabled: true,
@@ -2723,6 +1747,6 @@ function buildSelectorPath(element, maxAncestors = 5) {
2723
1747
  return parts.join(" > ");
2724
1748
  }
2725
1749
 
2726
- export { ALWAYS_BLOCK_SELECTORS, DEFAULT_AUTOCAPTURE_CONFIG, MAX_ANCESTORS, PRIORITY_ATTRIBUTES, SENSITIVE_ATTRIBUTES, buildSelectorPath, closeGuidePreview, definePlugin, filterHumanClasses, guidesPlugin, hasDocument, hasLocalStorage, hasNavigatorSendBeacon, hasWindow, previewGuide, runPreviewMode, uuidv7 };
2727
- //# sourceMappingURL=chunk-BBAA5BRS.mjs.map
2728
- //# sourceMappingURL=chunk-BBAA5BRS.mjs.map
1750
+ export { ALWAYS_BLOCK_SELECTORS, BannerRenderer, CustomRenderer, DEFAULT_AUTOCAPTURE_CONFIG, DEFAULT_TRACKER_BATCH_SIZE, DEFAULT_TRACKER_FLUSH_INTERVAL_MS, DEFAULT_TRACKER_MAX_RETRIES, FREQUENCY_CACHE_KEY_PREFIX, FREQUENCY_CACHE_MAX_ENTRIES, FREQUENCY_CACHE_TTL_MS, FormRenderer, InlineCustomRenderer, InlineFormRenderer, InlineRenderer, MAX_ANCESTORS, ModalRenderer, PRIORITY_ATTRIBUTES, SENSITIVE_ATTRIBUTES, TooltipRenderer, WALKTHROUGH_ABANDONMENT_TIMEOUT_MS, WALKTHROUGH_STATE_KEY_PREFIX, WalkthroughRenderer, buildSelectorPath, clearBuilderToken, closeGuidePreview, filterHumanClasses, hasDocument, hasLocalStorage, hasNavigatorSendBeacon, hasWindow, isBuilderMode, previewGuide, resolveBuilderOrigin, resolveBuilderToken, uuidv7 };
1751
+ //# sourceMappingURL=chunk-CI7NWEH2.mjs.map
1752
+ //# sourceMappingURL=chunk-CI7NWEH2.mjs.map