pulse-analytics-sdk 0.0.0-stage → 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.
package/dist/index.js ADDED
@@ -0,0 +1,1394 @@
1
+ "use strict";
2
+ "use client";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
+
23
+ // src/index.ts
24
+ var index_exports = {};
25
+ __export(index_exports, {
26
+ Analytics: () => Analytics,
27
+ flushAnalytics: () => flushAnalytics,
28
+ identifyUser: () => identifyUser,
29
+ trackEvent: () => trackEvent
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+ var import_react = require("react");
33
+
34
+ // ../../node_modules/.pnpm/web-vitals@6.2.3/node_modules/web-vitals/dist/web-vitals.js
35
+ var t = -1;
36
+ var n = () => t;
37
+ var e = (n2) => {
38
+ addEventListener("pageshow", (e2) => {
39
+ e2.persisted && (t = e2.timeStamp, n2(e2));
40
+ }, true);
41
+ };
42
+ var i = (t2, n2, e2, i2) => {
43
+ let o2, s2;
44
+ return (a2) => {
45
+ n2.value >= 0 && (a2 || i2) && (s2 = n2.value - (o2 ?? 0), (s2 || void 0 === o2) && (o2 = n2.value, n2.delta = s2, n2.rating = ((t3, n3) => t3 > n3[1] ? "poor" : t3 > n3[0] ? "needs-improvement" : "good")(n2.value, e2), t2(n2)));
46
+ };
47
+ };
48
+ var o = (t2) => {
49
+ requestAnimationFrame(() => requestAnimationFrame(() => t2()));
50
+ };
51
+ var s = () => {
52
+ const t2 = performance.getEntriesByType("navigation")[0];
53
+ if (t2 && t2.responseStart > 0 && t2.responseStart < performance.now()) return t2;
54
+ };
55
+ var a = () => s()?.activationStart ?? 0;
56
+ var r = -1;
57
+ var c = /* @__PURE__ */ new Set();
58
+ var f = () => "hidden" !== document.visibilityState || document.prerendering ? 1 / 0 : 0;
59
+ var h = (t2) => {
60
+ if ("hidden" === document.visibilityState) {
61
+ if ("visibilitychange" === t2.type) for (const t3 of c) t3();
62
+ isFinite(r) || (r = "visibilitychange" === t2.type ? t2.timeStamp : 0, removeEventListener("prerenderingchange", h, true));
63
+ }
64
+ };
65
+ var d = (t2 = false) => {
66
+ if (t2 && (r = 1 / 0), r < 0) {
67
+ const t3 = a(), n2 = document.prerendering ? void 0 : globalThis.performance.getEntriesByType("visibility-state").find((n3) => "hidden" === n3.name && n3.startTime >= t3)?.startTime;
68
+ r = n2 ?? f(), addEventListener("visibilitychange", h, true), addEventListener("prerenderingchange", h, true), e(() => {
69
+ setTimeout(() => {
70
+ r = f();
71
+ });
72
+ });
73
+ }
74
+ return { get firstHiddenTime() {
75
+ return r;
76
+ }, onHidden(t3) {
77
+ c.add(t3);
78
+ } };
79
+ };
80
+ var l = (t2, e2 = -1, i2, o2 = 0, r2, c2, f2) => {
81
+ const h2 = s(), d2 = h2?.navigationId || 0;
82
+ let l2 = "navigate";
83
+ i2 ? l2 = i2 : n() >= 0 ? l2 = "back-forward-cache" : h2 && (document.prerendering || a() > 0 ? l2 = "prerender" : document.wasDiscarded ? l2 = "restore" : h2.type && (l2 = h2.type.replace(/_/g, "-")));
84
+ return { name: t2, value: e2, rating: "good", delta: 0, entries: [], id: `v6-${Date.now()}-${Math.floor(8999999999999 * Math.random()) + 1e12}`, navigationType: l2, navigationId: o2 || d2, navigationInteractionId: r2, navigationURL: c2 || h2?.name, navigationStartTime: f2 || 0 };
85
+ };
86
+ var g = /* @__PURE__ */ new WeakMap();
87
+ function u(t2, n2) {
88
+ let e2 = g.get(n2);
89
+ return e2 || (e2 = /* @__PURE__ */ new WeakMap(), g.set(n2, e2)), e2.get(t2) || e2.set(t2, new n2()), e2.get(t2);
90
+ }
91
+ var v = class {
92
+ constructor() {
93
+ __publicField(this, "t");
94
+ __publicField(this, "i", 0);
95
+ __publicField(this, "o", []);
96
+ }
97
+ h(t2) {
98
+ if (t2.hadRecentInput) return;
99
+ const n2 = this.o[0], e2 = this.o.at(-1);
100
+ this.i && n2 && e2 && t2.startTime - e2.startTime < 1e3 && t2.startTime - n2.startTime < 5e3 ? (this.i += t2.value, this.o.push(t2)) : (this.i = t2.value, this.o = [t2]), this.t?.(t2);
101
+ }
102
+ };
103
+ var m = (t2, n2, e2 = {}) => {
104
+ try {
105
+ const i2 = t2.filter((t3) => PerformanceObserver.supportedEntryTypes.includes(t3));
106
+ if (i2.length > 0) {
107
+ const t3 = new PerformanceObserver((t4) => {
108
+ queueMicrotask(() => {
109
+ const e3 = t4.getEntries();
110
+ i2.length > 1 && e3.sort((t5, n3) => t5.startTime + t5.duration - (n3.startTime + n3.duration)), n2(e3);
111
+ });
112
+ });
113
+ for (const n3 of i2) t3.observe({ type: n3, buffered: true, ...e2 });
114
+ return t3;
115
+ }
116
+ } catch {
117
+ }
118
+ };
119
+ var p = (t2) => globalThis.PerformanceObserver?.supportedEntryTypes?.includes("soft-navigation") && "function" == typeof globalThis.PerformanceSoftNavigation?.prototype?.getLargestInteractionContentfulPaint && t2 && t2.reportSoftNavs;
120
+ var b = (t2, n2) => {
121
+ if (t2.set(n2.navigationId, n2), t2.size > 2) {
122
+ const n3 = t2.keys().next().value;
123
+ void 0 !== n3 && t2.delete(n3);
124
+ }
125
+ };
126
+ var T = (t2) => {
127
+ let n2 = false;
128
+ return () => {
129
+ n2 || (t2(), n2 = true);
130
+ };
131
+ };
132
+ var y = class {
133
+ constructor() {
134
+ __publicField(this, "l");
135
+ }
136
+ };
137
+ var _ = (t2) => {
138
+ document.prerendering ? addEventListener("prerenderingchange", t2, true) : t2();
139
+ };
140
+ var E = [1800, 3e3];
141
+ var M = (t2, s2 = {}) => {
142
+ const r2 = p(s2);
143
+ _(() => {
144
+ const c2 = u(s2, y), f2 = d();
145
+ let h2, g2 = l("FCP");
146
+ const v2 = m(["paint"], (t3) => {
147
+ for (const n2 of t3) "first-contentful-paint" === n2.name && (v2.disconnect(), n2.startTime < f2.firstHiddenTime && (g2.value = Math.max(n2.startTime - a(), 0), g2.entries.push(n2), g2.navigationId = n2.navigationId || g2.navigationId, h2(true)));
148
+ });
149
+ if (v2 && (h2 = i(t2, g2, E, s2.reportAllChanges), e((e2) => {
150
+ g2 = l("FCP", -1, "back-forward-cache", g2.navigationId, g2.navigationInteractionId, g2.navigationURL, n()), h2 = i(t2, g2, E, s2.reportAllChanges), o(() => {
151
+ g2.value = performance.now() - e2.timeStamp, h2(true);
152
+ });
153
+ })), r2) {
154
+ m(["soft-navigation"], (n2) => {
155
+ n2.forEach((n3) => {
156
+ c2.l && n3.navigationId && b(c2.l, n3);
157
+ const e2 = Math.max((n3.presentationTime || n3.paintTime || 0) - n3.startTime, 0);
158
+ g2 = l("FCP", e2, "soft-navigation", n3.navigationId, n3.interactionId, n3.name, n3.startTime), h2 = i(t2, g2, E, s2.reportAllChanges), h2(true);
159
+ });
160
+ }, s2);
161
+ }
162
+ });
163
+ };
164
+ var L = [0.1, 0.25];
165
+ var P = (t2, s2 = {}) => {
166
+ const a2 = d();
167
+ M(T(() => {
168
+ let r2, c2 = l("CLS", 0);
169
+ const f2 = u(s2, v), h2 = (n2, e2, o2, a3, h3) => {
170
+ c2 = l("CLS", 0, n2, e2, o2, a3, h3), f2.i = 0, r2 = i(t2, c2, L, s2.reportAllChanges);
171
+ }, d2 = (t3 = false) => {
172
+ f2.i > c2.value && (c2.value = f2.i, c2.entries = f2.o), r2(t3);
173
+ }, g2 = (t3) => {
174
+ d2(true), h2("soft-navigation", t3.navigationId, t3.interactionId, t3.name, t3.startTime);
175
+ }, b2 = (t3) => {
176
+ for (const n2 of t3) "soft-navigation" !== n2.entryType ? f2.h(n2) : g2(n2);
177
+ d2();
178
+ }, T2 = ["layout-shift"];
179
+ p(s2) && T2.push("soft-navigation");
180
+ const y2 = m(T2, b2);
181
+ y2 && (r2 = i(t2, c2, L, s2.reportAllChanges), a2.onHidden(() => {
182
+ b2(y2.takeRecords()), r2(true);
183
+ }), e(() => {
184
+ h2("back-forward-cache", c2.navigationId, c2.navigationInteractionId, c2.navigationURL, n()), o(r2);
185
+ }), setTimeout(r2));
186
+ }));
187
+ };
188
+ var w = 0;
189
+ var I = 1 / 0;
190
+ var k = 0;
191
+ var C = (t2) => {
192
+ for (const n2 of t2) n2.interactionId && (I = Math.min(I, n2.interactionId), k = Math.max(k, n2.interactionId), w = k ? (k - I) / 7 + 1 : 0);
193
+ };
194
+ var F;
195
+ var N = () => F ? w : performance.interactionCount ?? 0;
196
+ var B = () => {
197
+ "interactionCount" in performance || F || (F = m(["event"], C, { durationThreshold: 0 }));
198
+ };
199
+ var S = class {
200
+ constructor() {
201
+ __publicField(this, "u", 0);
202
+ __publicField(this, "v", []);
203
+ __publicField(this, "m", /* @__PURE__ */ new Map());
204
+ __publicField(this, "p");
205
+ __publicField(this, "T");
206
+ }
207
+ _() {
208
+ return N() - this.u;
209
+ }
210
+ M() {
211
+ this.u = N(), this.v.length = 0, this.m.clear();
212
+ }
213
+ L(t2) {
214
+ const n2 = this._(), e2 = Math.min(this.v.length - 1, Math.floor(n2 / 50));
215
+ return !n2 || -1 !== e2 || "soft-navigation" !== t2 && "back-forward-cache" !== t2 ? this.v[e2] : { P: 8, id: -1, entries: [] };
216
+ }
217
+ h(t2) {
218
+ if (this.p?.(t2), !t2.interactionId) return;
219
+ const n2 = this.v.at(-1);
220
+ let e2 = this.m.get(t2.interactionId);
221
+ if (e2 || this.v.length < 10 || t2.duration > n2.P) {
222
+ if (e2 ? t2.duration > e2.P ? (e2.entries = [t2], e2.P = t2.duration) : t2.duration === e2.P && t2.startTime === e2.entries[0].startTime && e2.entries.push(t2) : (e2 = { id: t2.interactionId, entries: [t2], P: t2.duration }, this.m.set(e2.id, e2), this.v.push(e2)), this.v.sort((t3, n3) => n3.P - t3.P), this.v.length > 10) {
223
+ const t3 = this.v.splice(10);
224
+ for (const n3 of t3) this.m.delete(n3.id);
225
+ }
226
+ this.T?.(e2);
227
+ }
228
+ }
229
+ };
230
+ var q = (t2) => {
231
+ const n2 = "requestIdleCallback" in globalThis ? 1e3 : 0, e2 = globalThis.requestIdleCallback || setTimeout, i2 = globalThis.cancelIdleCallback || clearTimeout;
232
+ if ("hidden" === document.visibilityState) t2();
233
+ else {
234
+ const o2 = T(t2);
235
+ let s2 = -1;
236
+ const a2 = () => {
237
+ i2(s2), o2();
238
+ };
239
+ addEventListener("visibilitychange", a2, { once: true, capture: true }), s2 = e2(() => {
240
+ removeEventListener("visibilitychange", a2, { capture: true }), o2();
241
+ }, { timeout: n2 });
242
+ }
243
+ };
244
+ var A = [200, 500];
245
+ var x = (t2, o2 = {}) => {
246
+ if (!globalThis.PerformanceEventTiming || !("interactionId" in PerformanceEventTiming.prototype)) return;
247
+ const s2 = d();
248
+ _(() => {
249
+ B();
250
+ let a2, r2 = l("INP");
251
+ const c2 = u(o2, S), f2 = (n2, e2, s3, f3, h3) => {
252
+ c2.M(), r2 = l("INP", -1, n2, e2, s3, f3, h3), a2 = i(t2, r2, A, o2.reportAllChanges);
253
+ }, h2 = () => {
254
+ const t3 = c2.L(r2.navigationType);
255
+ t3 && t3.P !== r2.value && (r2.value = t3.P, r2.entries = t3.entries, a2());
256
+ }, d2 = (t3) => {
257
+ h2(), a2(true), f2("soft-navigation", t3.navigationId, t3.interactionId, t3.name, t3.startTime);
258
+ }, g2 = (t3, n2 = false) => {
259
+ q(() => {
260
+ for (const n3 of t3) "soft-navigation" !== n3.entryType ? c2.h(n3) : d2(n3);
261
+ h2(), n2 && a2(true);
262
+ });
263
+ }, v2 = ["event", "first-input"];
264
+ p(o2) && v2.push("soft-navigation");
265
+ const b2 = m(v2, g2, { ...o2, durationThreshold: o2.durationThreshold ?? 40 });
266
+ a2 = i(t2, r2, A, o2.reportAllChanges), b2 && (s2.onHidden(() => {
267
+ g2(b2.takeRecords(), true);
268
+ }), e(() => {
269
+ f2("back-forward-cache", r2.navigationId, r2.navigationInteractionId, r2.navigationURL, n());
270
+ }));
271
+ });
272
+ };
273
+ var H = class {
274
+ constructor() {
275
+ __publicField(this, "p");
276
+ __publicField(this, "l");
277
+ }
278
+ h(t2) {
279
+ this.p?.(t2);
280
+ }
281
+ };
282
+ var O = [2500, 4e3];
283
+ var U = (t2, s2 = {}) => {
284
+ let r2 = false;
285
+ const c2 = p(s2);
286
+ _(() => {
287
+ let f2, h2 = d(), g2 = l("LCP");
288
+ const v2 = u(s2, H), p2 = (n2, e2, o2, a2, c3) => {
289
+ g2 = l("LCP", -1, n2, e2, o2, a2, c3), f2 = i(t2, g2, O, s2.reportAllChanges), r2 = false, "soft-navigation" === n2 && (h2 = d(true));
290
+ }, T2 = (t3) => {
291
+ v2.l && t3.navigationId && b(v2.l, t3), r2 || f2(true), p2("soft-navigation", t3.navigationId, t3.interactionId, t3.name, t3.startTime);
292
+ const n2 = t3.getLargestInteractionContentfulPaint?.();
293
+ n2 && y2([n2]);
294
+ }, y2 = (t3) => {
295
+ s2.reportAllChanges || c2 || (t3 = t3.slice(-1));
296
+ for (const n2 of t3) {
297
+ if (!n2) continue;
298
+ if ("soft-navigation" === n2.entryType) {
299
+ T2(n2);
300
+ continue;
301
+ }
302
+ let t4 = 0, e2 = [], i2 = n2.startTime;
303
+ if ("largest-contentful-paint" === n2.entryType) t4 = Math.max(n2.startTime - a(), 0), v2.h(n2), e2 = [n2];
304
+ else if ("interaction-contentful-paint" === n2.entryType) {
305
+ const o2 = n2;
306
+ if (!g2.navigationId) continue;
307
+ if ("interactionId" in o2 && o2.interactionId != g2.navigationInteractionId) continue;
308
+ i2 = o2.largestContentfulPaint?.renderTime || 0, t4 = Math.max(i2 - n2.startTime, 0), o2.largestContentfulPaint && (v2.h(o2.largestContentfulPaint), e2 = [o2.largestContentfulPaint]);
309
+ }
310
+ i2 < h2.firstHiddenTime && (g2.value = t4, g2.entries = e2, f2());
311
+ }
312
+ }, _2 = ["largest-contentful-paint"];
313
+ c2 && _2.push("interaction-contentful-paint", "soft-navigation");
314
+ const E2 = m(_2, y2);
315
+ if (E2) {
316
+ f2 = i(t2, g2, O, s2.reportAllChanges);
317
+ const a2 = ["keydown", "click", "visibilitychange"], h3 = (t3) => {
318
+ if (t3.isTrusted && !r2) {
319
+ const t4 = g2.id;
320
+ q(() => {
321
+ if (!r2) {
322
+ if (!c2) {
323
+ E2.disconnect();
324
+ for (const t5 of a2) removeEventListener(t5, h3, { capture: true });
325
+ }
326
+ t4 === g2.id && (r2 = true, f2(true));
327
+ }
328
+ });
329
+ }
330
+ };
331
+ for (const t3 of a2) addEventListener(t3, h3, { capture: true });
332
+ e((e2) => {
333
+ p2("back-forward-cache", g2.navigationId, g2.navigationInteractionId, g2.navigationURL, n()), f2 = i(t2, g2, O, s2.reportAllChanges), o(() => {
334
+ g2.value = performance.now() - e2.timeStamp, r2 = true, f2(true);
335
+ });
336
+ });
337
+ }
338
+ });
339
+ };
340
+ var W = [800, 1800];
341
+ var $ = (t2) => {
342
+ document.prerendering ? _(() => $(t2)) : "complete" !== document.readyState ? addEventListener("load", () => $(t2), true) : setTimeout(t2);
343
+ };
344
+ var D = (t2, o2 = {}) => {
345
+ const r2 = p(o2);
346
+ let c2 = l("TTFB"), f2 = i(t2, c2, W, o2.reportAllChanges);
347
+ $(() => {
348
+ const h2 = s();
349
+ if (h2) {
350
+ const s2 = h2.responseStart;
351
+ if (c2.value = Math.max(s2 - a(), 0), c2.entries = [h2], f2(true), e(() => {
352
+ c2 = l("TTFB", 0, "back-forward-cache", c2.navigationId, c2.navigationInteractionId, c2.navigationURL, n()), f2 = i(t2, c2, W, o2.reportAllChanges), f2(true);
353
+ }), r2) {
354
+ m(["soft-navigation"], (n2) => {
355
+ n2.forEach((n3) => {
356
+ n3.navigationId && (c2 = l("TTFB", 0, "soft-navigation", n3.navigationId, n3.interactionId, n3.name, n3.startTime), c2.entries = [n3], f2 = i(t2, c2, W, o2.reportAllChanges), f2(true));
357
+ });
358
+ }, o2);
359
+ }
360
+ }
361
+ });
362
+ };
363
+
364
+ // src/dom.ts
365
+ var INTERACTIVE_SELECTOR = "a, button, input, select, textarea, label, option, summary, details, video[controls], audio[controls], [role='button'], [role='link'], [role='menuitem'], [role='tab'], [role='checkbox'], [role='radio'], [role='switch'], [role='option'], [role='combobox'], [contenteditable='true'], [tabindex]:not([tabindex='-1'])";
366
+ var DOWNLOAD_EXT_RE = /\.(pdf|zip|tar|gz|tgz|rar|7z|csv|xlsx?|docx?|pptx?|json|txt|exe|dmg|pkg|msi|apk)$/i;
367
+ function getCssSelector(el) {
368
+ const parts = [];
369
+ let current = el;
370
+ let depth = 0;
371
+ while (current && current.nodeType === 1 && depth < 4) {
372
+ let part = current.tagName.toLowerCase();
373
+ if (current.id) {
374
+ part += `#${current.id}`;
375
+ parts.unshift(part);
376
+ break;
377
+ }
378
+ if (typeof current.className === "string" && current.className.trim()) {
379
+ const classes = current.className.trim().split(/\s+/).filter((cls) => cls && !cls.includes(":")).slice(0, 2).join(".");
380
+ if (classes) part += `.${classes}`;
381
+ }
382
+ parts.unshift(part);
383
+ current = current.parentElement;
384
+ depth += 1;
385
+ }
386
+ return parts.join(" > ").slice(0, 500);
387
+ }
388
+ function getClickLabel(el) {
389
+ const aria = el.getAttribute("aria-label") || el.getAttribute("title");
390
+ if (aria && aria.trim()) return aria.trim().slice(0, 160);
391
+ const text = el.innerText || el.textContent || "";
392
+ return text.replace(/\s+/g, " ").trim().slice(0, 160);
393
+ }
394
+ function parseQueryParams(searchParams) {
395
+ const result = {};
396
+ let count = 0;
397
+ searchParams.forEach((rawValue, rawKey) => {
398
+ if (count >= 25) return;
399
+ const key = rawKey.slice(0, 80);
400
+ const value = rawValue.slice(0, 240);
401
+ const existing = result[key];
402
+ if (existing === void 0) {
403
+ result[key] = value;
404
+ count += 1;
405
+ } else if (Array.isArray(existing)) {
406
+ if (existing.length < 10) existing.push(value);
407
+ } else {
408
+ result[key] = [existing, value];
409
+ }
410
+ });
411
+ return result;
412
+ }
413
+ function getScrollPercent() {
414
+ const doc = document.documentElement;
415
+ const body = document.body;
416
+ const scrollHeight = Math.max(
417
+ doc?.scrollHeight || 0,
418
+ body?.scrollHeight || 0,
419
+ window.innerHeight || 1,
420
+ 1
421
+ );
422
+ const viewportBottom = window.scrollY + (window.innerHeight || 0);
423
+ const pct = Math.round(viewportBottom / scrollHeight * 100);
424
+ return Math.max(0, Math.min(100, pct));
425
+ }
426
+ function classifyAnchorClick(anchor) {
427
+ const rawHref = anchor.getAttribute("href");
428
+ if (!rawHref || rawHref.startsWith("javascript:") || rawHref.startsWith("#")) {
429
+ return null;
430
+ }
431
+ try {
432
+ const resolved = new URL(rawHref, window.location.href);
433
+ const isHttp = resolved.protocol === "http:" || resolved.protocol === "https:";
434
+ const isExternal = isHttp && resolved.origin !== window.location.origin;
435
+ const downloadAttr = anchor.getAttribute("download");
436
+ const hasDownloadAttr = anchor.hasAttribute("download");
437
+ const extMatch = resolved.pathname.match(DOWNLOAD_EXT_RE);
438
+ if (hasDownloadAttr || isHttp && extMatch) {
439
+ const safeHref = resolved.protocol === "blob:" || resolved.protocol === "data:" ? `${resolved.protocol}//${downloadAttr || "download"}` : resolved.href;
440
+ const filename = downloadAttr && downloadAttr.trim() || resolved.pathname.split("/").pop() || "download";
441
+ const extFromName = filename.includes(".") ? filename.split(".").pop()?.toLowerCase() : void 0;
442
+ return {
443
+ kind: "download",
444
+ href: safeHref.slice(0, 1e3),
445
+ filename: filename.slice(0, 200),
446
+ extension: (extMatch?.[1] || extFromName || "").toLowerCase() || void 0,
447
+ targetHost: isHttp ? resolved.hostname : void 0,
448
+ isExternal
449
+ };
450
+ }
451
+ if (isExternal) {
452
+ return {
453
+ kind: "outbound",
454
+ href: resolved.href.slice(0, 1e3),
455
+ targetHost: resolved.hostname,
456
+ targetOrigin: resolved.origin,
457
+ targetPath: resolved.pathname,
458
+ isExternal: true
459
+ };
460
+ }
461
+ return {
462
+ kind: "internal",
463
+ href: rawHref.slice(0, 1e3),
464
+ isExternal: false
465
+ };
466
+ } catch {
467
+ return null;
468
+ }
469
+ }
470
+ function getFormIdentifier(form) {
471
+ const explicit = form.getAttribute("data-analytics-form") || form.id || form.getAttribute("name") || form.getAttribute("aria-label");
472
+ if (explicit && explicit.trim()) return explicit.trim().slice(0, 160);
473
+ const action = form.getAttribute("action");
474
+ if (action && action.trim()) {
475
+ try {
476
+ const url = new URL(action, window.location.href);
477
+ return `form:${url.pathname}`.slice(0, 160);
478
+ } catch {
479
+ return `form:${action.trim()}`.slice(0, 160);
480
+ }
481
+ }
482
+ return getCssSelector(form).slice(0, 160);
483
+ }
484
+ function getFieldDescriptor(el) {
485
+ if (!(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement)) {
486
+ return null;
487
+ }
488
+ if (el instanceof HTMLInputElement) {
489
+ if (el.type === "hidden" || el.type === "submit" || el.type === "button") {
490
+ return null;
491
+ }
492
+ if (el.type === "password") {
493
+ return el.name ? `password:${el.name.slice(0, 40)}` : "password_field";
494
+ }
495
+ }
496
+ const label = el.getAttribute("name") || el.id || el.getAttribute("aria-label") || (el instanceof HTMLInputElement ? el.type : el.tagName.toLowerCase());
497
+ return label ? label.trim().slice(0, 80) : null;
498
+ }
499
+
500
+ // src/transport.ts
501
+ var MAX_QUEUE_SIZE = 25;
502
+ var MAX_BATCH_BYTES = 6e3;
503
+ var queue = [];
504
+ var queuedEndpoint = "";
505
+ var queuedAppId = "";
506
+ var fetchLaterResult = null;
507
+ var fetchLaterController = null;
508
+ function randomId(prefix) {
509
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
510
+ return `${prefix}_${crypto.randomUUID()}`;
511
+ }
512
+ return `${prefix}_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
513
+ }
514
+ function getVisitorId() {
515
+ try {
516
+ const key = "__pulse_vid";
517
+ let vid = window.localStorage.getItem(key);
518
+ if (!vid) {
519
+ vid = randomId("v");
520
+ window.localStorage.setItem(key, vid);
521
+ }
522
+ return vid;
523
+ } catch {
524
+ return randomId("v");
525
+ }
526
+ }
527
+ function getSessionId() {
528
+ try {
529
+ const key = "__pulse_sid";
530
+ const tsKey = "__pulse_sts";
531
+ const now = Date.now();
532
+ const last = Number(window.sessionStorage.getItem(tsKey) || "0");
533
+ let sid = window.sessionStorage.getItem(key);
534
+ if (!sid || now - last > 30 * 60 * 1e3) {
535
+ sid = randomId("s");
536
+ window.sessionStorage.setItem(key, sid);
537
+ }
538
+ window.sessionStorage.setItem(tsKey, String(now));
539
+ return sid;
540
+ } catch {
541
+ return randomId("s");
542
+ }
543
+ }
544
+ function ensureFetchLater() {
545
+ const g2 = globalThis;
546
+ if (typeof g2.fetchLater === "function") {
547
+ return g2.fetchLater.bind(globalThis);
548
+ }
549
+ const polyfill = (url, init = {}) => {
550
+ let timeoutHandle;
551
+ let activated = false;
552
+ function sendNow() {
553
+ if (!(init.signal && init.signal.aborted)) {
554
+ if ("keepalive" in Request.prototype || init.method !== "POST" || init.headers) {
555
+ void fetch(url, Object.assign({}, init, { keepalive: true })).catch(
556
+ () => {
557
+ }
558
+ );
559
+ activated = true;
560
+ } else if (typeof navigator.sendBeacon === "function") {
561
+ activated = navigator.sendBeacon(
562
+ typeof url === "string" ? url : url.toString(),
563
+ init.body
564
+ );
565
+ }
566
+ }
567
+ destroy();
568
+ }
569
+ function destroy() {
570
+ if (typeof document !== "undefined") {
571
+ document.removeEventListener("visibilitychange", sendNow);
572
+ }
573
+ if (timeoutHandle !== void 0) {
574
+ clearTimeout(timeoutHandle);
575
+ }
576
+ }
577
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") {
578
+ queueMicrotask(sendNow);
579
+ } else {
580
+ if (typeof document !== "undefined") {
581
+ document.addEventListener("visibilitychange", sendNow);
582
+ }
583
+ if (typeof init.activateAfter === "number" && init.activateAfter >= 0) {
584
+ timeoutHandle = setTimeout(sendNow, init.activateAfter);
585
+ }
586
+ }
587
+ if (init.signal) {
588
+ init.signal.addEventListener("abort", destroy);
589
+ }
590
+ return {
591
+ get activated() {
592
+ return activated;
593
+ }
594
+ };
595
+ };
596
+ g2.fetchLater = polyfill;
597
+ return polyfill;
598
+ }
599
+ function buildEventRecord(config, payload) {
600
+ const url = new URL(window.location.href);
601
+ const queryStr = url.search || void 0;
602
+ const queryParams = url.search ? parseQueryParams(url.searchParams) : void 0;
603
+ return {
604
+ appId: config.appId,
605
+ visitorId: getVisitorId(),
606
+ sessionId: getSessionId(),
607
+ userId: config.userId ?? void 0,
608
+ userEmail: config.userEmail ?? void 0,
609
+ userTraits: config.userTraits ?? void 0,
610
+ path: payload.path ?? url.pathname,
611
+ query: payload.query ?? queryStr,
612
+ queryParams: payload.queryParams ?? queryParams,
613
+ url: payload.url ?? url.href,
614
+ title: payload.title ?? document.title,
615
+ referrer: document.referrer || void 0,
616
+ screenWidth: window.screen?.width,
617
+ screenHeight: window.screen?.height,
618
+ viewportWidth: window.innerWidth,
619
+ viewportHeight: window.innerHeight,
620
+ language: navigator.language,
621
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
622
+ utmSource: url.searchParams.get("utm_source") ?? void 0,
623
+ utmMedium: url.searchParams.get("utm_medium") ?? void 0,
624
+ utmCampaign: url.searchParams.get("utm_campaign") ?? void 0,
625
+ ...payload
626
+ };
627
+ }
628
+ function resetQueueState() {
629
+ fetchLaterController = null;
630
+ fetchLaterResult = null;
631
+ queue = [];
632
+ }
633
+ function sendFallbackDirect(endpoint, body) {
634
+ try {
635
+ void fetch(endpoint, {
636
+ method: "POST",
637
+ headers: { "Content-Type": "application/json" },
638
+ body,
639
+ keepalive: true
640
+ }).catch(() => {
641
+ });
642
+ } catch {
643
+ if (typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
644
+ navigator.sendBeacon(endpoint, new Blob([body], { type: "text/plain" }));
645
+ }
646
+ }
647
+ }
648
+ function scheduleBatch(endpoint, appId, activateAfterMs) {
649
+ if (queue.length === 0) return;
650
+ const body = JSON.stringify({
651
+ appId,
652
+ events: queue
653
+ });
654
+ if (fetchLaterController) {
655
+ fetchLaterController.abort();
656
+ }
657
+ fetchLaterController = new AbortController();
658
+ try {
659
+ const fetchLater = ensureFetchLater();
660
+ fetchLaterResult = fetchLater(endpoint, {
661
+ method: "POST",
662
+ headers: { "content-type": "application/json" },
663
+ body,
664
+ signal: fetchLaterController.signal,
665
+ activateAfter: activateAfterMs
666
+ });
667
+ } catch {
668
+ resetQueueState();
669
+ sendFallbackDirect(endpoint, body);
670
+ }
671
+ }
672
+ function enqueueEvent(config, payload, immediate = false) {
673
+ if (typeof window === "undefined") return;
674
+ if (fetchLaterResult?.activated || queue.length >= MAX_QUEUE_SIZE || queuedEndpoint && queuedEndpoint !== config.endpoint || queuedAppId && queuedAppId !== config.appId) {
675
+ resetQueueState();
676
+ }
677
+ queuedEndpoint = config.endpoint;
678
+ queuedAppId = config.appId;
679
+ const record = buildEventRecord(config, payload);
680
+ const candidate = [...queue, record];
681
+ const candidateBytes = JSON.stringify({
682
+ appId: config.appId,
683
+ events: candidate
684
+ }).length;
685
+ if (candidateBytes > MAX_BATCH_BYTES && queue.length > 0) {
686
+ const previousBody = JSON.stringify({
687
+ appId: config.appId,
688
+ events: queue
689
+ });
690
+ if (fetchLaterController) {
691
+ fetchLaterController.abort();
692
+ }
693
+ resetQueueState();
694
+ sendFallbackDirect(config.endpoint, previousBody);
695
+ }
696
+ queue.push(record);
697
+ scheduleBatch(
698
+ config.endpoint,
699
+ config.appId,
700
+ immediate ? 0 : config.batchWindowMs
701
+ );
702
+ }
703
+ function flushTelemetryQueue() {
704
+ if (typeof window === "undefined") return;
705
+ if (fetchLaterResult?.activated || queue.length === 0 || !queuedEndpoint) {
706
+ return;
707
+ }
708
+ const body = JSON.stringify({
709
+ appId: queuedAppId,
710
+ events: queue
711
+ });
712
+ if (fetchLaterController) {
713
+ fetchLaterController.abort();
714
+ }
715
+ resetQueueState();
716
+ sendFallbackDirect(queuedEndpoint, body);
717
+ }
718
+
719
+ // src/index.ts
720
+ var IDLE_THRESHOLD_MS = 3e4;
721
+ var RAGE_WINDOW_MS = 1e3;
722
+ var RAGE_MIN_CLICKS = 3;
723
+ var RAGE_RADIUS_PX = 32;
724
+ var DEAD_CLICK_OBSERVE_MS = 350;
725
+ var SCROLL_MILESTONES = [25, 50, 75, 100];
726
+ var activeConfig = null;
727
+ var vitalsRegistered = false;
728
+ var currentVitalPath = "/";
729
+ function trackEvent(eventName, props) {
730
+ if (!activeConfig) return;
731
+ enqueueEvent(activeConfig, {
732
+ eventType: "custom",
733
+ eventName,
734
+ props: props ?? {}
735
+ });
736
+ }
737
+ function identifyUser(userId, traits) {
738
+ if (!activeConfig) return;
739
+ activeConfig.userId = userId;
740
+ if (traits?.email) activeConfig.userEmail = traits.email;
741
+ if (traits) activeConfig.userTraits = traits;
742
+ }
743
+ function flushAnalytics() {
744
+ flushTelemetryQueue();
745
+ }
746
+ function Analytics({
747
+ appId,
748
+ endpoint,
749
+ userId,
750
+ userEmail,
751
+ userTraits,
752
+ trackPageviews = true,
753
+ trackClicks = true,
754
+ trackScrollDepth = true,
755
+ trackEngagement = true,
756
+ trackFriction = true,
757
+ trackOutbound = true,
758
+ trackForms = true,
759
+ trackErrors = true,
760
+ trackWebVitals = true,
761
+ batchWindowMs = 2e3,
762
+ disabled = false
763
+ }) {
764
+ const configRef = (0, import_react.useRef)({
765
+ appId,
766
+ endpoint,
767
+ userId,
768
+ userEmail,
769
+ userTraits,
770
+ batchWindowMs
771
+ });
772
+ (0, import_react.useEffect)(() => {
773
+ const nextConfig = {
774
+ appId,
775
+ endpoint,
776
+ userId,
777
+ userEmail,
778
+ userTraits,
779
+ batchWindowMs
780
+ };
781
+ configRef.current = nextConfig;
782
+ activeConfig = disabled ? null : nextConfig;
783
+ }, [appId, endpoint, userId, userEmail, userTraits, batchWindowMs, disabled]);
784
+ (0, import_react.useEffect)(() => {
785
+ if (disabled || typeof window === "undefined") {
786
+ activeConfig = null;
787
+ return;
788
+ }
789
+ const getConfig = () => configRef.current;
790
+ activeConfig = configRef.current;
791
+ let activeRoute = null;
792
+ const initialPath = window.location.pathname;
793
+ let pageStartTs = Date.now();
794
+ let activeAccumMs = 0;
795
+ let lastTickTs = Date.now();
796
+ let lastInteractionTs = Date.now();
797
+ let lastMouseTs = 0;
798
+ let maxScrollDepth = 0;
799
+ const sentMilestones = /* @__PURE__ */ new Set();
800
+ let titleTimer = null;
801
+ let titleRaf = null;
802
+ let initialScrollTimer = null;
803
+ let pendingPageviewEmit = null;
804
+ let leaveSentForRoute = false;
805
+ const recentClicks = [];
806
+ const trackedForms = /* @__PURE__ */ new Map();
807
+ const reportedErrors = /* @__PURE__ */ new Set();
808
+ const deadClickCleanups = /* @__PURE__ */ new Set();
809
+ const updateActiveTime = () => {
810
+ const now = Date.now();
811
+ const dt = Math.min(Math.max(0, now - lastTickTs), 1500);
812
+ if (trackEngagement && document.visibilityState === "visible" && now - lastInteractionTs <= IDLE_THRESHOLD_MS) {
813
+ activeAccumMs += dt;
814
+ }
815
+ lastTickTs = now;
816
+ };
817
+ const markInteraction = () => {
818
+ const now = Date.now();
819
+ updateActiveTime();
820
+ lastInteractionTs = now;
821
+ };
822
+ const handleMouseMove = () => {
823
+ const now = Date.now();
824
+ if (now - lastMouseTs < 500) return;
825
+ lastMouseTs = now;
826
+ markInteraction();
827
+ };
828
+ const cancelPendingTitleTimer = () => {
829
+ if (titleRaf !== null) {
830
+ window.cancelAnimationFrame(titleRaf);
831
+ titleRaf = null;
832
+ }
833
+ if (titleTimer !== null) {
834
+ window.clearTimeout(titleTimer);
835
+ titleTimer = null;
836
+ }
837
+ if (initialScrollTimer !== null) {
838
+ window.clearTimeout(initialScrollTimer);
839
+ initialScrollTimer = null;
840
+ }
841
+ };
842
+ const emitAbandonedForms = (snapshot, immediate) => {
843
+ if (!trackForms) return;
844
+ for (const state of trackedForms.values()) {
845
+ if (!state.submitted && !state.abandonedReported && state.fieldsTouched.size > 0) {
846
+ state.abandonedReported = true;
847
+ enqueueEvent(
848
+ getConfig(),
849
+ {
850
+ eventType: "form_abandon",
851
+ eventName: state.formId,
852
+ formId: state.formId,
853
+ path: snapshot.path,
854
+ query: snapshot.query,
855
+ queryParams: snapshot.queryParams,
856
+ url: snapshot.url,
857
+ title: document.title || snapshot.title,
858
+ durationMs: Math.max(0, Date.now() - state.startedAt),
859
+ props: {
860
+ formId: state.formId,
861
+ fieldsTouchedCount: state.fieldsTouched.size,
862
+ fieldCount: state.fieldCount,
863
+ fieldsTouched: Array.from(state.fieldsTouched).slice(0, 20)
864
+ }
865
+ },
866
+ immediate
867
+ );
868
+ }
869
+ }
870
+ };
871
+ const finalizeRouteLeave = (immediate) => {
872
+ if (!activeRoute || leaveSentForRoute) return;
873
+ if (pendingPageviewEmit) {
874
+ const flushPv = pendingPageviewEmit;
875
+ pendingPageviewEmit = null;
876
+ flushPv();
877
+ }
878
+ leaveSentForRoute = true;
879
+ updateActiveTime();
880
+ const durationMs = Math.max(0, Date.now() - pageStartTs);
881
+ const activeMs = Math.min(durationMs, Math.round(activeAccumMs));
882
+ if (trackScrollDepth) {
883
+ const doc = document.documentElement;
884
+ const scrollHeight = Math.max(
885
+ doc?.scrollHeight || 0,
886
+ document.body?.scrollHeight || 0,
887
+ 1
888
+ );
889
+ if (scrollHeight <= (window.innerHeight || 0) && activeMs > 300) {
890
+ maxScrollDepth = Math.max(maxScrollDepth, 100);
891
+ } else {
892
+ maxScrollDepth = Math.max(maxScrollDepth, getScrollPercent());
893
+ }
894
+ checkScrollMilestones();
895
+ }
896
+ emitAbandonedForms(activeRoute, immediate);
897
+ if (durationMs > 200) {
898
+ enqueueEvent(
899
+ getConfig(),
900
+ {
901
+ eventType: "leave",
902
+ path: activeRoute.path,
903
+ query: activeRoute.query,
904
+ queryParams: activeRoute.queryParams,
905
+ url: activeRoute.url,
906
+ title: document.title || activeRoute.title,
907
+ durationMs,
908
+ activeMs: trackEngagement ? activeMs : void 0,
909
+ scrollDepth: trackScrollDepth ? maxScrollDepth : void 0
910
+ },
911
+ immediate
912
+ );
913
+ }
914
+ };
915
+ const resetPageState = (url) => {
916
+ pageStartTs = Date.now();
917
+ activeAccumMs = 0;
918
+ lastTickTs = Date.now();
919
+ lastInteractionTs = Date.now();
920
+ maxScrollDepth = 0;
921
+ sentMilestones.clear();
922
+ recentClicks.length = 0;
923
+ trackedForms.clear();
924
+ leaveSentForRoute = false;
925
+ const snapshot = {
926
+ routeKey: url.pathname + url.search,
927
+ path: url.pathname,
928
+ query: url.search || void 0,
929
+ queryParams: url.search ? parseQueryParams(url.searchParams) : void 0,
930
+ url: url.href,
931
+ title: document.title
932
+ };
933
+ activeRoute = snapshot;
934
+ currentVitalPath = snapshot.path;
935
+ return snapshot;
936
+ };
937
+ let scrollThrottleTimer = null;
938
+ const checkScrollMilestones = () => {
939
+ if (!trackScrollDepth || !activeRoute) return;
940
+ const pct = getScrollPercent();
941
+ maxScrollDepth = Math.max(maxScrollDepth, pct);
942
+ for (const milestone of SCROLL_MILESTONES) {
943
+ if (pct >= milestone && !sentMilestones.has(milestone)) {
944
+ sentMilestones.add(milestone);
945
+ updateActiveTime();
946
+ enqueueEvent(getConfig(), {
947
+ eventType: "scroll",
948
+ eventName: `scroll_${milestone}`,
949
+ scrollDepth: milestone,
950
+ activeMs: trackEngagement ? Math.round(activeAccumMs) : void 0,
951
+ path: activeRoute.path,
952
+ query: activeRoute.query,
953
+ queryParams: activeRoute.queryParams,
954
+ url: activeRoute.url
955
+ });
956
+ }
957
+ }
958
+ };
959
+ const recordPageview = (deferMs) => {
960
+ const url = new URL(window.location.href);
961
+ const routeKey = url.pathname + url.search;
962
+ if (activeRoute && routeKey === activeRoute.routeKey) return;
963
+ cancelPendingTitleTimer();
964
+ if (activeRoute) {
965
+ finalizeRouteLeave(false);
966
+ }
967
+ const snapshot = resetPageState(url);
968
+ if (trackScrollDepth) {
969
+ initialScrollTimer = window.setTimeout(() => {
970
+ initialScrollTimer = null;
971
+ checkScrollMilestones();
972
+ }, 400);
973
+ }
974
+ if (!trackPageviews) return;
975
+ const emitPageview = () => {
976
+ pendingPageviewEmit = null;
977
+ snapshot.title = document.title;
978
+ enqueueEvent(getConfig(), {
979
+ eventType: "pageview",
980
+ path: snapshot.path,
981
+ query: snapshot.query,
982
+ queryParams: snapshot.queryParams,
983
+ url: snapshot.url,
984
+ title: snapshot.title
985
+ });
986
+ };
987
+ if (deferMs <= 0) {
988
+ emitPageview();
989
+ return;
990
+ }
991
+ pendingPageviewEmit = emitPageview;
992
+ titleRaf = window.requestAnimationFrame(() => {
993
+ titleRaf = null;
994
+ titleTimer = window.setTimeout(() => {
995
+ titleTimer = null;
996
+ emitPageview();
997
+ }, deferMs);
998
+ });
999
+ };
1000
+ recordPageview(50);
1001
+ const engagementInterval = trackEngagement ? window.setInterval(updateActiveTime, 1e3) : null;
1002
+ if (trackEngagement) {
1003
+ window.addEventListener("pointerdown", markInteraction, { passive: true });
1004
+ window.addEventListener("keydown", markInteraction, { passive: true });
1005
+ window.addEventListener("touchstart", markInteraction, { passive: true });
1006
+ window.addEventListener("wheel", markInteraction, { passive: true });
1007
+ window.addEventListener("mousemove", handleMouseMove, { passive: true });
1008
+ }
1009
+ const handleScroll = () => {
1010
+ if (trackEngagement) markInteraction();
1011
+ if (!trackScrollDepth || scrollThrottleTimer !== null) return;
1012
+ scrollThrottleTimer = window.setTimeout(() => {
1013
+ scrollThrottleTimer = null;
1014
+ checkScrollMilestones();
1015
+ }, 150);
1016
+ };
1017
+ if (trackScrollDepth || trackEngagement) {
1018
+ window.addEventListener("scroll", handleScroll, { passive: true });
1019
+ }
1020
+ const origPushState = window.history.pushState;
1021
+ const origReplaceState = window.history.replaceState;
1022
+ const handlePopState = () => recordPageview(140);
1023
+ const handlePageHide = () => {
1024
+ finalizeRouteLeave(true);
1025
+ flushTelemetryQueue();
1026
+ };
1027
+ const handleVisibilityChange = () => {
1028
+ updateActiveTime();
1029
+ if (document.visibilityState === "hidden") {
1030
+ finalizeRouteLeave(true);
1031
+ flushTelemetryQueue();
1032
+ } else {
1033
+ leaveSentForRoute = false;
1034
+ pageStartTs = Date.now();
1035
+ activeAccumMs = 0;
1036
+ lastTickTs = Date.now();
1037
+ lastInteractionTs = Date.now();
1038
+ }
1039
+ };
1040
+ if (trackPageviews || trackEngagement || trackForms || trackScrollDepth) {
1041
+ window.history.pushState = function(...args) {
1042
+ origPushState.apply(this, args);
1043
+ recordPageview(140);
1044
+ };
1045
+ window.history.replaceState = function(...args) {
1046
+ origReplaceState.apply(this, args);
1047
+ recordPageview(140);
1048
+ };
1049
+ window.addEventListener("popstate", handlePopState);
1050
+ window.addEventListener("pagehide", handlePageHide);
1051
+ document.addEventListener("visibilitychange", handleVisibilityChange);
1052
+ }
1053
+ const handleClick = (event) => {
1054
+ if (trackEngagement) markInteraction();
1055
+ const target = event.target;
1056
+ if (!target) return;
1057
+ const interactiveEl = target.closest(INTERACTIVE_SELECTOR) ?? target;
1058
+ const vw = window.innerWidth || 1;
1059
+ const vh = window.innerHeight || 1;
1060
+ const clickX = Math.round(event.clientX);
1061
+ const clickY = Math.round(event.clientY);
1062
+ const clickXPct = Number((event.clientX / vw * 100).toFixed(2));
1063
+ const clickYPct = Number((event.clientY / vh * 100).toFixed(2));
1064
+ const clickTag = interactiveEl.tagName.toLowerCase();
1065
+ const clickText = getClickLabel(interactiveEl);
1066
+ const clickSelector = getCssSelector(interactiveEl);
1067
+ const anchor = target.closest("a");
1068
+ let anchorInfo = null;
1069
+ if (anchor instanceof HTMLAnchorElement) {
1070
+ anchorInfo = classifyAnchorClick(anchor);
1071
+ }
1072
+ if (trackOutbound && anchorInfo) {
1073
+ if (anchorInfo.kind === "download") {
1074
+ enqueueEvent(getConfig(), {
1075
+ eventType: "download",
1076
+ eventName: anchorInfo.filename,
1077
+ clickTag,
1078
+ clickText,
1079
+ clickSelector,
1080
+ clickHref: anchorInfo.href,
1081
+ clickX,
1082
+ clickY,
1083
+ clickXPct,
1084
+ clickYPct,
1085
+ isOutbound: anchorInfo.isExternal,
1086
+ props: {
1087
+ filename: anchorInfo.filename,
1088
+ extension: anchorInfo.extension,
1089
+ targetHost: anchorInfo.targetHost
1090
+ }
1091
+ });
1092
+ } else if (anchorInfo.kind === "outbound") {
1093
+ enqueueEvent(getConfig(), {
1094
+ eventType: "outbound",
1095
+ eventName: anchorInfo.targetHost,
1096
+ clickTag,
1097
+ clickText,
1098
+ clickSelector,
1099
+ clickHref: anchorInfo.href,
1100
+ clickX,
1101
+ clickY,
1102
+ clickXPct,
1103
+ clickYPct,
1104
+ isOutbound: true,
1105
+ props: {
1106
+ targetHost: anchorInfo.targetHost,
1107
+ targetOrigin: anchorInfo.targetOrigin,
1108
+ targetPath: anchorInfo.targetPath
1109
+ }
1110
+ });
1111
+ }
1112
+ }
1113
+ if (trackClicks) {
1114
+ enqueueEvent(getConfig(), {
1115
+ eventType: "click",
1116
+ clickTag,
1117
+ clickText,
1118
+ clickSelector,
1119
+ clickHref: anchor?.getAttribute("href") ?? void 0,
1120
+ clickX,
1121
+ clickY,
1122
+ clickXPct,
1123
+ clickYPct,
1124
+ isOutbound: anchorInfo?.isExternal ?? void 0
1125
+ });
1126
+ }
1127
+ if (trackFriction) {
1128
+ const now = Date.now();
1129
+ while (recentClicks.length > 0 && now - recentClicks[0].ts > RAGE_WINDOW_MS) {
1130
+ recentClicks.shift();
1131
+ }
1132
+ const sample = {
1133
+ ts: now,
1134
+ x: clickX,
1135
+ y: clickY,
1136
+ selector: clickSelector,
1137
+ reported: false
1138
+ };
1139
+ recentClicks.push(sample);
1140
+ const cluster = recentClicks.filter(
1141
+ (c2) => c2.selector === sample.selector && Math.hypot(c2.x - sample.x, c2.y - sample.y) <= 80 || Math.hypot(c2.x - sample.x, c2.y - sample.y) <= RAGE_RADIUS_PX
1142
+ );
1143
+ if (cluster.length >= RAGE_MIN_CLICKS && !cluster.some((c2) => c2.reported)) {
1144
+ for (const c2 of cluster) c2.reported = true;
1145
+ enqueueEvent(getConfig(), {
1146
+ eventType: "rage_click",
1147
+ eventName: "rage_click",
1148
+ clickTag,
1149
+ clickText,
1150
+ clickSelector,
1151
+ clickX,
1152
+ clickY,
1153
+ clickXPct,
1154
+ clickYPct,
1155
+ props: {
1156
+ clickCount: cluster.length,
1157
+ windowMs: RAGE_WINDOW_MS
1158
+ }
1159
+ });
1160
+ }
1161
+ const isRootSurface = target === document.body || target === document.documentElement;
1162
+ const isInteractive = Boolean(target.closest(INTERACTIVE_SELECTOR));
1163
+ const hasTextSelection = Boolean(window.getSelection()?.toString().trim());
1164
+ if (!isRootSurface && !isInteractive && !hasTextSelection && document.body) {
1165
+ const startHref = window.location.href;
1166
+ let domMutated = false;
1167
+ const observer = new MutationObserver(() => {
1168
+ domMutated = true;
1169
+ });
1170
+ observer.observe(document.body, {
1171
+ childList: true,
1172
+ subtree: true,
1173
+ attributes: true,
1174
+ characterData: true
1175
+ });
1176
+ const timerId = window.setTimeout(() => {
1177
+ observer.disconnect();
1178
+ deadClickCleanups.delete(cleanupDeadClick);
1179
+ if (!domMutated && window.location.href === startHref) {
1180
+ enqueueEvent(getConfig(), {
1181
+ eventType: "dead_click",
1182
+ eventName: "dead_click",
1183
+ clickTag: target.tagName.toLowerCase(),
1184
+ clickText: getClickLabel(target),
1185
+ clickSelector: getCssSelector(target),
1186
+ clickX,
1187
+ clickY,
1188
+ clickXPct,
1189
+ clickYPct
1190
+ });
1191
+ }
1192
+ }, DEAD_CLICK_OBSERVE_MS);
1193
+ const cleanupDeadClick = () => {
1194
+ window.clearTimeout(timerId);
1195
+ observer.disconnect();
1196
+ };
1197
+ deadClickCleanups.add(cleanupDeadClick);
1198
+ }
1199
+ }
1200
+ };
1201
+ if (trackClicks || trackFriction || trackOutbound) {
1202
+ document.addEventListener("click", handleClick, { capture: true });
1203
+ }
1204
+ const ensureFormState = (form) => {
1205
+ let state = trackedForms.get(form);
1206
+ if (!state) {
1207
+ const fieldCount = form.querySelectorAll(
1208
+ "input:not([type='hidden']):not([type='submit']):not([type='button']), select, textarea"
1209
+ ).length;
1210
+ state = {
1211
+ formId: getFormIdentifier(form),
1212
+ fieldsTouched: /* @__PURE__ */ new Set(),
1213
+ fieldCount,
1214
+ startedAt: Date.now(),
1215
+ submitted: false,
1216
+ abandonedReported: false
1217
+ };
1218
+ trackedForms.set(form, state);
1219
+ }
1220
+ return state;
1221
+ };
1222
+ const handleFormInteraction = (event) => {
1223
+ if (!trackForms) return;
1224
+ const target = event.target;
1225
+ if (!target) return;
1226
+ const form = target.closest("form");
1227
+ if (!(form instanceof HTMLFormElement)) return;
1228
+ const descriptor = getFieldDescriptor(target);
1229
+ if (!descriptor) return;
1230
+ const state = ensureFormState(form);
1231
+ state.fieldsTouched.add(descriptor);
1232
+ };
1233
+ const handleFormSubmit = (event) => {
1234
+ if (!trackForms) return;
1235
+ const form = event.target;
1236
+ if (!(form instanceof HTMLFormElement)) return;
1237
+ const state = ensureFormState(form);
1238
+ state.submitted = true;
1239
+ enqueueEvent(getConfig(), {
1240
+ eventType: "form_submit",
1241
+ eventName: state.formId,
1242
+ formId: state.formId,
1243
+ durationMs: Math.max(0, Date.now() - state.startedAt),
1244
+ props: {
1245
+ formId: state.formId,
1246
+ fieldsTouchedCount: state.fieldsTouched.size,
1247
+ fieldCount: state.fieldCount
1248
+ }
1249
+ });
1250
+ };
1251
+ if (trackForms) {
1252
+ document.addEventListener("focusin", handleFormInteraction, {
1253
+ capture: true
1254
+ });
1255
+ document.addEventListener("change", handleFormInteraction, {
1256
+ capture: true
1257
+ });
1258
+ document.addEventListener("submit", handleFormSubmit, {
1259
+ capture: true
1260
+ });
1261
+ }
1262
+ const emitError = (kind, name, message, stack, extra) => {
1263
+ const dedupeKey = `${kind}:${message}`;
1264
+ if (reportedErrors.has(dedupeKey) || reportedErrors.size >= 50) return;
1265
+ reportedErrors.add(dedupeKey);
1266
+ enqueueEvent(getConfig(), {
1267
+ eventType: "error",
1268
+ eventName: name.slice(0, 120),
1269
+ errorMessage: message.slice(0, 500),
1270
+ errorStack: stack?.slice(0, 1500),
1271
+ props: {
1272
+ kind,
1273
+ ...extra
1274
+ }
1275
+ });
1276
+ };
1277
+ const handleWindowError = (event) => {
1278
+ const errObj = event.error instanceof Error ? event.error : null;
1279
+ const message = errObj?.message || event.message || "Unknown script error";
1280
+ const name = errObj?.name || "Error";
1281
+ emitError("error", name, message, errObj?.stack, {
1282
+ source: event.filename?.slice(0, 300),
1283
+ lineno: event.lineno,
1284
+ colno: event.colno
1285
+ });
1286
+ };
1287
+ const handleUnhandledRejection = (event) => {
1288
+ const reason = event.reason;
1289
+ const errObj = reason instanceof Error ? reason : null;
1290
+ const message = errObj?.message || (typeof reason === "string" ? reason : "Unhandled promise rejection");
1291
+ const name = errObj?.name || "UnhandledRejection";
1292
+ emitError("unhandledrejection", name, message, errObj?.stack);
1293
+ };
1294
+ if (trackErrors) {
1295
+ window.addEventListener("error", handleWindowError);
1296
+ window.addEventListener("unhandledrejection", handleUnhandledRejection);
1297
+ }
1298
+ if (trackWebVitals && !vitalsRegistered) {
1299
+ vitalsRegistered = true;
1300
+ const reportVital = (metric) => {
1301
+ const cfg = activeConfig;
1302
+ if (!cfg) return;
1303
+ const decimals = metric.name === "CLS" ? 4 : 2;
1304
+ const vitalPath = metric.name === "LCP" || metric.name === "TTFB" ? initialPath : currentVitalPath;
1305
+ enqueueEvent(cfg, {
1306
+ eventType: "web_vital",
1307
+ eventName: metric.name,
1308
+ path: vitalPath,
1309
+ metricName: metric.name,
1310
+ metricValue: Number(metric.value.toFixed(decimals)),
1311
+ metricRating: metric.rating,
1312
+ props: {
1313
+ id: metric.id,
1314
+ delta: Number(metric.delta.toFixed(decimals)),
1315
+ navigationType: metric.navigationType
1316
+ }
1317
+ });
1318
+ };
1319
+ U(reportVital);
1320
+ x(reportVital);
1321
+ P(reportVital);
1322
+ D(reportVital);
1323
+ }
1324
+ return () => {
1325
+ cancelPendingTitleTimer();
1326
+ if (scrollThrottleTimer !== null) {
1327
+ window.clearTimeout(scrollThrottleTimer);
1328
+ }
1329
+ if (engagementInterval !== null) {
1330
+ window.clearInterval(engagementInterval);
1331
+ }
1332
+ for (const cleanup of deadClickCleanups) cleanup();
1333
+ deadClickCleanups.clear();
1334
+ if (trackEngagement) {
1335
+ window.removeEventListener("pointerdown", markInteraction);
1336
+ window.removeEventListener("keydown", markInteraction);
1337
+ window.removeEventListener("touchstart", markInteraction);
1338
+ window.removeEventListener("wheel", markInteraction);
1339
+ window.removeEventListener("mousemove", handleMouseMove);
1340
+ }
1341
+ if (trackScrollDepth || trackEngagement) {
1342
+ window.removeEventListener("scroll", handleScroll);
1343
+ }
1344
+ if (trackPageviews || trackEngagement || trackForms || trackScrollDepth) {
1345
+ window.history.pushState = origPushState;
1346
+ window.history.replaceState = origReplaceState;
1347
+ window.removeEventListener("popstate", handlePopState);
1348
+ window.removeEventListener("pagehide", handlePageHide);
1349
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
1350
+ }
1351
+ if (trackClicks || trackFriction || trackOutbound) {
1352
+ document.removeEventListener("click", handleClick, { capture: true });
1353
+ }
1354
+ if (trackForms) {
1355
+ document.removeEventListener("focusin", handleFormInteraction, {
1356
+ capture: true
1357
+ });
1358
+ document.removeEventListener("change", handleFormInteraction, {
1359
+ capture: true
1360
+ });
1361
+ document.removeEventListener("submit", handleFormSubmit, {
1362
+ capture: true
1363
+ });
1364
+ }
1365
+ if (trackErrors) {
1366
+ window.removeEventListener("error", handleWindowError);
1367
+ window.removeEventListener(
1368
+ "unhandledrejection",
1369
+ handleUnhandledRejection
1370
+ );
1371
+ }
1372
+ activeConfig = null;
1373
+ };
1374
+ }, [
1375
+ disabled,
1376
+ trackPageviews,
1377
+ trackClicks,
1378
+ trackScrollDepth,
1379
+ trackEngagement,
1380
+ trackFriction,
1381
+ trackOutbound,
1382
+ trackForms,
1383
+ trackErrors,
1384
+ trackWebVitals
1385
+ ]);
1386
+ return null;
1387
+ }
1388
+ // Annotate the CommonJS export names for ESM import in node:
1389
+ 0 && (module.exports = {
1390
+ Analytics,
1391
+ flushAnalytics,
1392
+ identifyUser,
1393
+ trackEvent
1394
+ });