@usermaven/nextjs 1.4.1-rc.58 → 1.4.1-rc.60

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.
@@ -0,0 +1,1625 @@
1
+ import * as React from 'react';
2
+ import { createContext, useContext, useCallback, useEffect, useState } from 'react';
3
+
4
+ const UsermavenContext = createContext(null);
5
+
6
+ const UsermavenProvider = function ({ children, client }) {
7
+ const Context = UsermavenContext;
8
+ return React.createElement(Context.Provider, { value: client }, children);
9
+ };
10
+
11
+ var v = /* @__PURE__ */ ((s) => (s[s.DEBUG = 0] = "DEBUG", s[s.INFO = 1] = "INFO", s[s.WARN = 2] = "WARN", s[s.ERROR = 3] = "ERROR", s))(v || {});
12
+ class J {
13
+ constructor(e) {
14
+ this.level = e;
15
+ }
16
+ debug(e, ...t) {
17
+ this.level <= 0 && console.debug("[Usermaven Debug]:", e, ...t);
18
+ }
19
+ info(e, ...t) {
20
+ this.level <= 1 && console.info("[Usermaven Info]:", e, ...t);
21
+ }
22
+ warn(e, ...t) {
23
+ this.level <= 2 && console.warn("[Usermaven Warning]:", e, ...t);
24
+ }
25
+ error(e, ...t) {
26
+ this.level <= 3 && console.error("[Usermaven Error]:", e, ...t);
27
+ }
28
+ }
29
+ function h(s = 0) {
30
+ return new J(s);
31
+ }
32
+ const D = {
33
+ logLevel: v.ERROR,
34
+ useBeaconApi: !1,
35
+ forceUseFetch: !1,
36
+ trackingHost: "t.usermaven.com",
37
+ autocapture: !1,
38
+ rageClick: !1,
39
+ formTracking: !1,
40
+ autoPageview: !1,
41
+ disableEventPersistence: !1,
42
+ gaHook: !1,
43
+ segmentHook: !1,
44
+ randomizeUrl: !1,
45
+ capture3rdPartyCookies: ["_ga", "_fbp", "_ym_uid", "ajs_user_id", "ajs_anonymous_id"],
46
+ idMethod: "cookie",
47
+ ipPolicy: "keep",
48
+ cookiePolicy: "keep",
49
+ minSendTimeout: 0,
50
+ maxSendTimeout: 2e3,
51
+ maxSendAttempts: 4,
52
+ propertiesStringMaxLength: null,
53
+ propertyBlacklist: [],
54
+ crossDomainLinking: !0,
55
+ maskAllText: !1,
56
+ maskAllElementAttributes: !1
57
+ };
58
+ class Q {
59
+ constructor(e) {
60
+ this.domain = e, this.cookieDomain = this.getCookieDomain(), console.log(this.cookieDomain);
61
+ }
62
+ set(e, t, i = 365, n = !0, r = !1) {
63
+ console.log("Setting cookie", e, t, i, n, r);
64
+ const o = /* @__PURE__ */ new Date();
65
+ o.setTime(o.getTime() + i * 24 * 60 * 60 * 1e3);
66
+ const c = `expires=${o.toUTCString()}`, l = n ? "; Secure" : "", a = r ? "; HttpOnly" : "";
67
+ document.cookie = `${e}=${t};${c};path=/;domain=${this.cookieDomain}${l}${a}`;
68
+ }
69
+ get(e) {
70
+ const t = e + "=", i = document.cookie.split(";");
71
+ for (let n = 0; n < i.length; n++) {
72
+ let r = i[n].trim();
73
+ if (r.indexOf(t) === 0)
74
+ return decodeURIComponent(r.substring(t.length));
75
+ }
76
+ return null;
77
+ }
78
+ delete(e, t = "/") {
79
+ document.cookie = `${e}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${t};domain=${this.cookieDomain}`;
80
+ }
81
+ getCookieDomain() {
82
+ return typeof window > "u" || this.domain ? this.domain || "" : this.extractRoot(window.location.hostname);
83
+ }
84
+ extractRoot(e) {
85
+ if (this.isIpAddress(e) || e === "localhost")
86
+ return e;
87
+ let t = this.extractTopLevelDomain(e);
88
+ return t || (t = this.extractRootDomain(e)), "." + t;
89
+ }
90
+ isIpAddress(e) {
91
+ const t = e.split(".");
92
+ return t.length === 4 && t.every((i) => !isNaN(Number(i)));
93
+ }
94
+ extractHostname(e) {
95
+ let t;
96
+ return e.indexOf("//") > -1 ? t = e.split("/")[2] : t = e.split("/")[0], t = t.split(":")[0], t = t.split("?")[0], t;
97
+ }
98
+ extractRootDomain(e) {
99
+ let t = this.extractHostname(e);
100
+ const i = t.split("."), n = i.length;
101
+ return n > 2 && (i[n - 1].length == 2 ? (t = i[n - 2] + "." + i[n - 1], i[n - 2].length == 2 && (t = i[n - 3] + "." + t)) : t = i[n - 2] + "." + i[n - 1]), t;
102
+ }
103
+ extractTopLevelDomain(e) {
104
+ const t = /[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i, i = e.match(t);
105
+ return i ? i[0] : "";
106
+ }
107
+ }
108
+ const W = Object.prototype, X = W.hasOwnProperty, K = Array.prototype, E = K.forEach, T = {};
109
+ function Z(s, e, t) {
110
+ if (Array.isArray(s)) {
111
+ if (E && s.forEach === E)
112
+ s.forEach(e, t);
113
+ else if ("length" in s && s.length === +s.length) {
114
+ for (let i = 0, n = s.length; i < n; i++)
115
+ if (i in s && e.call(t, s[i], i) === T)
116
+ return;
117
+ }
118
+ }
119
+ }
120
+ const A = function(s) {
121
+ return s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
122
+ }, G = function(s) {
123
+ for (const e in s)
124
+ typeof s[e] == "function" && (s[e] = s[e].bind(s));
125
+ };
126
+ function S(s, e, t) {
127
+ if (s != null) {
128
+ if (E && Array.isArray(s) && s.forEach === E)
129
+ s.forEach(e, t);
130
+ else if ("length" in s && s.length === +s.length) {
131
+ for (let i = 0, n = s.length; i < n; i++)
132
+ if (i in s && e.call(t, s[i], i) === T)
133
+ return;
134
+ } else
135
+ for (const i in s)
136
+ if (X.call(s, i) && e.call(t, s[i], i) === T)
137
+ return;
138
+ }
139
+ }
140
+ const Y = function(s, ...e) {
141
+ return Z(e, function(t) {
142
+ for (const i in t)
143
+ t[i] !== void 0 && (s[i] = t[i]);
144
+ }), s;
145
+ };
146
+ function _(s, e) {
147
+ return s.indexOf(e) !== -1;
148
+ }
149
+ const F = function(s) {
150
+ try {
151
+ return /^\s*\bfunction\b/.test(s);
152
+ } catch {
153
+ return !1;
154
+ }
155
+ }, j = function(s) {
156
+ return s === void 0;
157
+ }, p = function() {
158
+ const s = function(i, n, r, o, c) {
159
+ if (!i) {
160
+ h().error("No valid element provided to register_event");
161
+ return;
162
+ }
163
+ if (i.addEventListener && !o)
164
+ i.addEventListener(n, r, !!c);
165
+ else {
166
+ const l = "on" + n, a = i[l];
167
+ i[l] = e(i, r, a);
168
+ }
169
+ };
170
+ function e(i, n, r) {
171
+ return function(o) {
172
+ if (o = o || t(window.event), !o)
173
+ return;
174
+ let c = !0, l;
175
+ F(r) && (l = r(o));
176
+ const a = n.call(i, o);
177
+ return (l === !1 || a === !1) && (c = !1), c;
178
+ };
179
+ }
180
+ function t(i) {
181
+ return i && (i.preventDefault = t.preventDefault, i.stopPropagation = t.stopPropagation), i;
182
+ }
183
+ return t.preventDefault = function() {
184
+ this.returnValue = !1;
185
+ }, t.stopPropagation = function() {
186
+ this.cancelBubble = !0;
187
+ }, s;
188
+ }(), ee = function(s) {
189
+ return function(...e) {
190
+ try {
191
+ return s.apply(this, e);
192
+ } catch (t) {
193
+ h().error("Implementation error. Please turn on debug and contact support@usermaven.com.", t);
194
+ }
195
+ };
196
+ }, z = function(s) {
197
+ for (const e in s)
198
+ typeof s[e] == "function" && (s[e] = ee(s[e]));
199
+ };
200
+ function N(s) {
201
+ for (let e in s)
202
+ (s[e] === "" || s[e] === null || s[e] === void 0 || typeof s[e] == "object" && Object.keys(s[e]).length === 0) && delete s[e];
203
+ return s;
204
+ }
205
+ function u() {
206
+ try {
207
+ return typeof window < "u" && window.document !== void 0 && window.document.createElement !== void 0;
208
+ } catch {
209
+ return h().warn("window is not available"), !1;
210
+ }
211
+ }
212
+ function f(s = 5) {
213
+ const e = new Uint8Array(s);
214
+ return crypto.getRandomValues(e), Array.from(e, (t) => t.toString(36).padStart(2, "0")).join("").slice(0, s);
215
+ }
216
+ function te(s) {
217
+ return s.replace(
218
+ /([-_][a-z])/g,
219
+ (e) => e.toUpperCase().replace("-", "").replace("_", "")
220
+ );
221
+ }
222
+ function C(s) {
223
+ return typeof s != "object" || s === null ? s : Array.isArray(s) ? s.map(C) : Object.keys(s).reduce((e, t) => {
224
+ const i = te(t);
225
+ return e[i] = C(s[t]), e;
226
+ }, {});
227
+ }
228
+ function P(s) {
229
+ switch (typeof s.className) {
230
+ case "string":
231
+ return s.className;
232
+ case "object":
233
+ return ("baseVal" in s.className ? s.className.baseVal : null) || s.getAttribute("class") || "";
234
+ default:
235
+ return "";
236
+ }
237
+ }
238
+ function O(s) {
239
+ let e = "";
240
+ return M(s) && !q(s) && s.childNodes && s.childNodes.length && S(s.childNodes, function(t) {
241
+ B(t) && t.textContent && (e += A(t.textContent).split(/(\s+)/).filter(H).join("").replace(/[\r\n]/g, " ").replace(/[ ]+/g, " ").substring(0, 255));
242
+ }), A(e);
243
+ }
244
+ function R(s) {
245
+ return !!s && s.nodeType === 1;
246
+ }
247
+ function d(s, e) {
248
+ return !!s && !!s.tagName && s.tagName.toLowerCase() === e.toLowerCase();
249
+ }
250
+ function B(s) {
251
+ return !!s && s.nodeType === 3;
252
+ }
253
+ function x(s) {
254
+ return !!s && s.nodeType === 11;
255
+ }
256
+ const b = ["a", "button", "form", "input", "select", "textarea", "label"];
257
+ function ie(s, e) {
258
+ if (!s || d(s, "html") || !R(s))
259
+ return !1;
260
+ let t = s;
261
+ for (; t && !d(t, "body"); ) {
262
+ if (t.classList && t.classList.contains("um-no-capture"))
263
+ return !1;
264
+ t.parentNode && x(t.parentNode) ? t = t.parentNode.host : t = t.parentNode;
265
+ }
266
+ let i = !1;
267
+ for (t = s; t && !d(t, "body"); ) {
268
+ if (t.parentNode && x(t.parentNode)) {
269
+ t = t.parentNode.host, t && b.indexOf(t.tagName.toLowerCase()) > -1 && (i = !0);
270
+ continue;
271
+ }
272
+ const o = t.parentNode;
273
+ if (!o) break;
274
+ if (b.indexOf(o.tagName.toLowerCase()) > -1)
275
+ i = !0;
276
+ else {
277
+ const c = window.getComputedStyle(o);
278
+ c && c.getPropertyValue("cursor") === "pointer" && (i = !0);
279
+ }
280
+ t = o;
281
+ }
282
+ const n = window.getComputedStyle(s);
283
+ if (n && n.getPropertyValue("cursor") === "pointer" && e.type === "click")
284
+ return !0;
285
+ const r = s.tagName.toLowerCase();
286
+ switch (r) {
287
+ case "html":
288
+ return !1;
289
+ case "form":
290
+ return e.type === "submit";
291
+ case "input":
292
+ return e.type === "change" || e.type === "click";
293
+ case "select":
294
+ case "textarea":
295
+ return e.type === "change" || e.type === "click";
296
+ default:
297
+ return i ? e.type === "click" : e.type === "click" && (b.indexOf(r) > -1 || s.getAttribute("contenteditable") === "true");
298
+ }
299
+ }
300
+ function M(s) {
301
+ if (!s || !R(s))
302
+ return !1;
303
+ if (typeof s.hasAttribute == "function") {
304
+ if (s.hasAttribute(w.FORCE_CAPTURE_ATTR))
305
+ return !0;
306
+ if (s.hasAttribute(w.PREVENT_CAPTURE_ATTR))
307
+ return !1;
308
+ }
309
+ let e = s;
310
+ for (; e && e.parentElement && !d(e, "body"); ) {
311
+ const n = P(e).split(" ");
312
+ if (_(n, "ph-sensitive") || _(n, "ph-no-capture"))
313
+ return !1;
314
+ e = e.parentElement;
315
+ }
316
+ if (_(P(s).split(" "), "ph-include"))
317
+ return !0;
318
+ const t = s.type;
319
+ if (typeof t == "string")
320
+ switch (t.toLowerCase()) {
321
+ case "hidden":
322
+ case "password":
323
+ return !1;
324
+ }
325
+ const i = s.name || s.id || "";
326
+ return !(typeof i == "string" && /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g, "")));
327
+ }
328
+ function q(s) {
329
+ const e = ["button", "checkbox", "submit", "reset"];
330
+ return !!(d(s, "input") && !e.includes(s.type) || d(s, "select") || d(s, "textarea") || s.getAttribute("contenteditable") === "true");
331
+ }
332
+ function H(s) {
333
+ return !(s === null || j(s) || typeof s == "string" && (s = A(s), /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((s || "").replace(/[- ]/g, "")) || /(^\d{3}-?\d{2}-?\d{4}$)/.test(s)));
334
+ }
335
+ function se(s) {
336
+ return typeof s == "string" ? s.substring(0, 10) === "_ngcontent" || s.substring(0, 7) === "_nghost" : !1;
337
+ }
338
+ function $() {
339
+ return f(10);
340
+ }
341
+ function ne(s) {
342
+ return /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(s).toLowerCase());
343
+ }
344
+ function re(s, e) {
345
+ let t;
346
+ return function(...i) {
347
+ const n = () => {
348
+ clearTimeout(t), s(...i);
349
+ };
350
+ clearTimeout(t), t = setTimeout(n, e);
351
+ };
352
+ }
353
+ function oe(s) {
354
+ const e = {}, t = s.replace(/^\?/, "").split("&");
355
+ for (let i = 0; i < t.length; i++) {
356
+ const n = t[i].split("=");
357
+ n[0] !== "" && (e[decodeURIComponent(n[0])] = decodeURIComponent(n[1] || ""));
358
+ }
359
+ return e;
360
+ }
361
+ function L(s) {
362
+ return typeof s == "string" || s instanceof String;
363
+ }
364
+ function k(s) {
365
+ return s !== null && typeof s == "object" && s.constructor === Object;
366
+ }
367
+ function ae(s) {
368
+ if (s === null)
369
+ return v.ERROR;
370
+ const e = s.toUpperCase(), t = v[e];
371
+ return t || t === 0 ? t : v.ERROR;
372
+ }
373
+ class ce {
374
+ constructor(e) {
375
+ this.maxScrollDepth = 0, this.milestones = [25, 50, 75, 90], this.lastScrollDepth = 0, this.client = e, this.documentElement = document.documentElement, this.debouncedHandleScroll = re(this.handleScroll.bind(this), 250), this.initializeEventListener();
376
+ }
377
+ initializeEventListener() {
378
+ window.addEventListener("scroll", this.debouncedHandleScroll);
379
+ }
380
+ track() {
381
+ const e = this.getScrollDepth();
382
+ e > this.lastScrollDepth && (this.lastScrollDepth = e, this.checkMilestones(e));
383
+ }
384
+ send(e = "$scroll") {
385
+ const t = {
386
+ percent: this.lastScrollDepth,
387
+ window_height: this.getWindowHeight(),
388
+ document_height: this.getDocumentHeight(),
389
+ scroll_distance: this.getScrollDistance()
390
+ };
391
+ this.client.track(e, t);
392
+ }
393
+ handleScroll() {
394
+ this.track();
395
+ }
396
+ getScrollDepth() {
397
+ const e = this.getWindowHeight(), t = this.getDocumentHeight(), i = this.getScrollDistance(), n = t - e;
398
+ return Math.min(100, Math.floor(i / n * 100));
399
+ }
400
+ getWindowHeight() {
401
+ return window.innerHeight || this.documentElement.clientHeight || document.body.clientHeight || 0;
402
+ }
403
+ getDocumentHeight() {
404
+ return Math.max(
405
+ document.body.scrollHeight || 0,
406
+ this.documentElement.scrollHeight || 0,
407
+ document.body.offsetHeight || 0,
408
+ this.documentElement.offsetHeight || 0,
409
+ document.body.clientHeight || 0,
410
+ this.documentElement.clientHeight || 0
411
+ );
412
+ }
413
+ getScrollDistance() {
414
+ return window.pageYOffset || this.documentElement.scrollTop || document.body.scrollTop || 0;
415
+ }
416
+ checkMilestones(e) {
417
+ this.milestones.filter((i) => e >= i).forEach((i) => {
418
+ this.send(), this.milestones = this.milestones.filter((n) => n !== i);
419
+ });
420
+ }
421
+ }
422
+ const y = class y {
423
+ constructor(e, t, i = h()) {
424
+ this.logger = i, this.scrollDepth = null, this.client = e, this.options = t, this.scrollDepth = new ce(e), G(this), z(this);
425
+ }
426
+ init() {
427
+ if (!(document && document.body)) {
428
+ this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."), setTimeout(() => this.init(), 500);
429
+ return;
430
+ }
431
+ this.addDomEventHandlers();
432
+ }
433
+ addDomEventHandlers() {
434
+ const e = (t) => {
435
+ t = t || window.event, this.captureEvent(t);
436
+ };
437
+ p(document, "submit", e, !1, !0), p(document, "change", e, !1, !0), p(document, "click", e, !1, !0), p(document, "visibilitychange", e, !1, !0), p(document, "scroll", e, !1, !0), p(window, "popstate", e, !1, !0);
438
+ }
439
+ isPageRefresh() {
440
+ if ("PerformanceNavigationTiming" in window) {
441
+ const e = performance.getEntriesByType("navigation");
442
+ if (e.length > 0)
443
+ return e[0].type === "reload";
444
+ }
445
+ return performance.navigation && performance.navigation.type === 1;
446
+ }
447
+ captureEvent(e) {
448
+ var i, n;
449
+ let t = this.getEventTarget(e);
450
+ if (B(t) && (t = t.parentNode || null), e.type === "scroll")
451
+ return (i = this.scrollDepth) == null || i.track(), !0;
452
+ if (e.type === "visibilitychange" && document.visibilityState === "hidden" || e.type === "popstate")
453
+ return this.isPageRefresh() || (n = this.scrollDepth) == null || n.send(), !0;
454
+ if (t && this.shouldCaptureElement(t, e)) {
455
+ const r = this.getElementList(t), o = this.getElementsJson(r, e), c = Y(
456
+ this.getDefaultProperties(e.type),
457
+ {
458
+ $elements: o
459
+ }
460
+ );
461
+ return this.client.track("$autocapture", c), !0;
462
+ }
463
+ }
464
+ shouldCaptureElement(e, t) {
465
+ return !e || typeof e.hasAttribute != "function" ? !1 : e.hasAttribute(y.FORCE_CAPTURE_ATTR) ? !0 : e.hasAttribute(y.PREVENT_CAPTURE_ATTR) ? !1 : ie(e, t);
466
+ }
467
+ getEventTarget(e) {
468
+ var t;
469
+ return typeof e.target > "u" ? e.srcElement || null : (t = e.target) != null && t.shadowRoot ? e.composedPath()[0] || null : e.target || null;
470
+ }
471
+ getElementList(e) {
472
+ const t = [e];
473
+ let i = e;
474
+ for (; i.parentNode && !d(i, "body"); )
475
+ x(i.parentNode) ? (t.push(i.parentNode.host), i = i.parentNode.host) : (t.push(i.parentNode), i = i.parentNode);
476
+ return t;
477
+ }
478
+ getElementsJson(e, t) {
479
+ const i = [];
480
+ let n = null, r = !1;
481
+ return S(e, (o) => {
482
+ if (d(o, "a")) {
483
+ const l = o.getAttribute("href");
484
+ l !== null && M(o) && H(l) && (n = l);
485
+ }
486
+ const c = P(o).split(" ");
487
+ _(c, "ph-no-capture") && (r = !0), i.push(this.getPropertiesFromElement(o));
488
+ }), this.options.maskAllText || (i[0].$el_text = this.sanitizeText(O(e[0]))), n !== null && (i[0].attr__href = n), r ? [] : i;
489
+ }
490
+ getPropertiesFromElement(e) {
491
+ const t = {
492
+ tag_name: e.tagName.toLowerCase()
493
+ };
494
+ b.indexOf(t.tag_name) > -1 && !this.options.maskAllText && (t.$el_text = this.sanitizeText(O(e)));
495
+ const i = P(e);
496
+ i.length > 0 && (t.classes = i.split(" ").filter((c) => c !== "")), S(e.attributes, (c) => {
497
+ q(e) && ["name", "id", "class"].indexOf(c.name) === -1 || !this.options.maskAllElementAttributes && H(c.value) && !se(c.name) && (t["attr__" + c.name] = this.sanitizeAttributeValue(c.name, c.value));
498
+ });
499
+ let n = 1, r = 1, o = e;
500
+ for (; o = this.previousElementSibling(o); )
501
+ n++, o.tagName === e.tagName && r++;
502
+ return t.nth_child = n, t.nth_of_type = r, t;
503
+ }
504
+ previousElementSibling(e) {
505
+ if (e.previousElementSibling)
506
+ return e.previousElementSibling;
507
+ do
508
+ e = e.previousSibling;
509
+ while (e && !R(e));
510
+ return e;
511
+ }
512
+ getDefaultProperties(e) {
513
+ return {
514
+ $event_type: e,
515
+ $ce_version: 1
516
+ };
517
+ }
518
+ // Input sanitization and XSS prevention methods
519
+ sanitizeText(e) {
520
+ e = e.replace(/<[^>]*?>/g, ""), e = this.encodeHtml(e);
521
+ const t = this.options.propertiesStringMaxLength || 255;
522
+ return e.length > t && (e = e.substring(0, t) + "..."), e;
523
+ }
524
+ sanitizeUrl(e) {
525
+ if (!e) return "";
526
+ try {
527
+ const t = new URL(e, window.location.href);
528
+ return t.protocol !== "http:" && t.protocol !== "https:" ? "" : encodeURI(t.toString());
529
+ } catch {
530
+ return this.encodeHtml(e);
531
+ }
532
+ }
533
+ sanitizeAttributeValue(e, t) {
534
+ switch (e.toLowerCase()) {
535
+ case "href":
536
+ case "src":
537
+ return this.sanitizeUrl(t);
538
+ default:
539
+ return this.encodeHtml(t);
540
+ }
541
+ }
542
+ encodeHtml(e) {
543
+ return e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
544
+ }
545
+ static enabledForProject(e, t = 10, i = 10) {
546
+ if (!e)
547
+ return !1;
548
+ let n = 0;
549
+ for (let r = 0; r < e.length; r++)
550
+ n += e.charCodeAt(r);
551
+ return n % t < i;
552
+ }
553
+ static isBrowserSupported() {
554
+ return F(document.querySelectorAll);
555
+ }
556
+ };
557
+ y.FORCE_CAPTURE_ATTR = "data-um-force-capture", y.PREVENT_CAPTURE_ATTR = "data-um-no-capture";
558
+ let w = y;
559
+ class le {
560
+ constructor(e) {
561
+ this.client = e, this.lastPageUrl = window.location.href, this.trackInitialPageview(), this.initializePageviewTracking();
562
+ }
563
+ trackInitialPageview() {
564
+ this.trackPageview();
565
+ }
566
+ initializePageviewTracking() {
567
+ window.addEventListener("popstate", this.handlePageview.bind(this));
568
+ const e = history.pushState;
569
+ history.pushState = (...t) => {
570
+ e.apply(history, t), this.handlePageview();
571
+ }, window.addEventListener("hashchange", this.handlePageview.bind(this)), setInterval(this.checkForUrlChange.bind(this), 1e3);
572
+ }
573
+ handlePageview() {
574
+ this.trackPageview();
575
+ }
576
+ checkForUrlChange() {
577
+ window.location.href !== this.lastPageUrl && this.trackPageview();
578
+ }
579
+ trackPageview() {
580
+ const e = window.location.href;
581
+ e !== this.lastPageUrl && (this.lastPageUrl = e, this.client.track("pageview", {
582
+ url: e,
583
+ referrer: document.referrer,
584
+ title: document.title
585
+ }));
586
+ }
587
+ }
588
+ class ue {
589
+ constructor(e, t, i = h()) {
590
+ this.trackingHost = e, this.logger = i, this.config = t;
591
+ }
592
+ async send(e) {
593
+ const t = this.config.key, i = this.constructUrl(t), n = new Blob([JSON.stringify(e)], { type: "application/json" });
594
+ if (navigator.sendBeacon(i, n))
595
+ this.logger.debug(`Successfully queued ${e.length} event(s) via Beacon API`);
596
+ else
597
+ throw new Error("Failed to queue events via Beacon API");
598
+ }
599
+ constructUrl(e) {
600
+ const t = this.config.cookiePolicy !== "keep" ? `&cookie_policy=${this.config.cookiePolicy}` : "", i = this.config.ipPolicy !== "keep" ? `&ip_policy=${this.config.ipPolicy}` : "", n = u() ? "/api/v1/event" : "/api/v1/s2s/event";
601
+ return this.config.randomizeUrl ? `${this.trackingHost}/api.${f()}?p_${f()}=${e}${t}${i}` : `${this.trackingHost}${n}?token=${e}${t}${i}`;
602
+ }
603
+ // Note: Beacon API doesn't support custom headers, so we can't use them here.
604
+ // If custom headers are crucial, you might want to fall back to XHR or Fetch in those cases.
605
+ }
606
+ class U {
607
+ constructor(e, t, i = h()) {
608
+ this.trackingHost = e, this.logger = i, this.config = t;
609
+ }
610
+ async send(e) {
611
+ const t = this.config.key, i = this.constructUrl(t), n = JSON.stringify(e), r = {
612
+ "Content-Type": "application/json",
613
+ ...this.getCustomHeaders()
614
+ }, o = await fetch(i, {
615
+ method: "POST",
616
+ headers: r,
617
+ body: n
618
+ });
619
+ if (!o.ok)
620
+ throw new Error(`HTTP error! status: ${o.status}`);
621
+ this.logger.debug(`Successfully sent ${e.length} event(s)`), this.postHandle(o.status, await o.text());
622
+ }
623
+ constructUrl(e) {
624
+ const t = this.config.cookiePolicy !== "keep" ? `&cookie_policy=${this.config.cookiePolicy}` : "", i = this.config.ipPolicy !== "keep" ? `&ip_policy=${this.config.ipPolicy}` : "", n = u() ? "/api/v1/event" : "/api/v1/s2s/event";
625
+ return this.config.randomizeUrl ? `${this.trackingHost}/api.${f()}?p_${f()}=${e}${t}${i}` : `${this.trackingHost}${n}?token=${e}${t}${i}`;
626
+ }
627
+ getCustomHeaders() {
628
+ return typeof this.config.customHeaders == "function" ? this.config.customHeaders() : this.config.customHeaders ? this.config.customHeaders : {};
629
+ }
630
+ postHandle(e, t) {
631
+ this.logger.debug(`Response received. Status: ${e}, Body: ${t}`);
632
+ }
633
+ }
634
+ class he {
635
+ constructor(e, t, i = h()) {
636
+ this.trackingHost = e, this.logger = i, this.config = t;
637
+ }
638
+ send(e) {
639
+ return new Promise((t, i) => {
640
+ const n = new XMLHttpRequest(), r = this.config.key, o = this.constructUrl(r);
641
+ n.open("POST", o, !0), n.setRequestHeader("Content-Type", "application/json");
642
+ const c = this.getCustomHeaders();
643
+ Object.keys(c).forEach((l) => {
644
+ n.setRequestHeader(l, c[l]);
645
+ }), n.onload = () => {
646
+ n.status >= 200 && n.status < 300 ? (this.logger.debug(`Successfully sent ${e.length} event(s)`), t()) : i(new Error(`HTTP error! status: ${n.status}`));
647
+ }, n.onerror = () => {
648
+ i(new Error("Network error"));
649
+ }, n.send(JSON.stringify(e));
650
+ });
651
+ }
652
+ constructUrl(e) {
653
+ const t = this.config.cookiePolicy !== "keep" ? `&cookie_policy=${this.config.cookiePolicy}` : "", i = this.config.ipPolicy !== "keep" ? `&ip_policy=${this.config.ipPolicy}` : "", n = u() ? "/api/v1/event" : "/api/v1/s2s/event";
654
+ return this.config.randomizeUrl ? `${this.trackingHost}/api.${f()}?p_${f()}=${e}${t}${i}` : `${this.trackingHost}${n}?token=${e}${t}${i}`;
655
+ }
656
+ getCustomHeaders() {
657
+ return typeof this.config.customHeaders == "function" ? this.config.customHeaders() : this.config.customHeaders ? this.config.customHeaders : {};
658
+ }
659
+ postHandle(e, t) {
660
+ this.logger.debug(`Response received. Status: ${e}, Body: ${t}`);
661
+ }
662
+ }
663
+ class V {
664
+ constructor(e, t) {
665
+ this.storage = {}, this.prefix = `usermaven_${e}_`, this.load(), this.logger = t || h();
666
+ }
667
+ set(e, t) {
668
+ this.storage[e] = t, this.save();
669
+ }
670
+ get(e) {
671
+ return this.storage[e];
672
+ }
673
+ remove(e) {
674
+ delete this.storage[e], this.save();
675
+ }
676
+ clear() {
677
+ this.storage = {}, this.save();
678
+ }
679
+ save() {
680
+ if (!u()) {
681
+ this.logger.warn("localStorage is not available in this environment");
682
+ return;
683
+ }
684
+ try {
685
+ localStorage.setItem(this.prefix + "data", JSON.stringify(this.storage));
686
+ } catch (e) {
687
+ this.logger.error("Error saving to localStorage:", e);
688
+ }
689
+ }
690
+ load() {
691
+ if (!u()) {
692
+ this.logger.warn("localStorage is not available in this environment");
693
+ return;
694
+ }
695
+ try {
696
+ const e = localStorage.getItem(this.prefix + "data");
697
+ e && (this.storage = JSON.parse(e));
698
+ } catch (e) {
699
+ this.logger.error("Error loading from localStorage:", e);
700
+ }
701
+ }
702
+ }
703
+ class ge {
704
+ constructor() {
705
+ this.storage = {};
706
+ }
707
+ set(e, t) {
708
+ this.storage[e] = t;
709
+ }
710
+ get(e) {
711
+ return this.storage[e];
712
+ }
713
+ remove(e) {
714
+ delete this.storage[e];
715
+ }
716
+ save() {
717
+ }
718
+ clear() {
719
+ this.storage = {};
720
+ }
721
+ }
722
+ class I {
723
+ // Default to true for server-side
724
+ constructor(e, t = 3, i = 1e3, n = 10, r = 1e3, o = h()) {
725
+ this.transport = e, this.maxRetries = t, this.retryInterval = i, this.batchSize = n, this.batchInterval = r, this.logger = o, this.queue = [], this.processing = !1, this.batchTimeoutId = null, this.isOnline = !0, this.persistence = new V("offline_queue"), u() && (this.isOnline = navigator.onLine, this.loadQueueFromStorage(), this.initNetworkListeners(), this.scheduleBatch());
726
+ }
727
+ add(e) {
728
+ const t = { payload: e, retries: 0, timestamp: Date.now() };
729
+ this.queue.push(t), u() ? this.saveQueueToStorage() : this.processBatch();
730
+ }
731
+ initNetworkListeners() {
732
+ u() && (window.addEventListener("online", () => {
733
+ this.isOnline = !0, this.processBatch();
734
+ }), window.addEventListener("offline", () => {
735
+ this.isOnline = !1;
736
+ }));
737
+ }
738
+ scheduleBatch() {
739
+ u() && (this.batchTimeoutId !== null && clearTimeout(this.batchTimeoutId), this.batchTimeoutId = window.setTimeout(() => this.processBatch(), this.batchInterval));
740
+ }
741
+ async processBatch() {
742
+ if ((!u() || this.isOnline) && !this.processing && this.queue.length > 0) {
743
+ this.processing = !0;
744
+ const e = this.queue.splice(0, this.batchSize), t = e.map((i) => i.payload);
745
+ try {
746
+ await this.transport.send(t), this.logger.debug(`Successfully sent batch of ${e.length} payloads`), u() && this.saveQueueToStorage();
747
+ } catch (i) {
748
+ this.logger.error("Failed to send batch", i), await this.handleBatchFailure(e);
749
+ }
750
+ this.processing = !1;
751
+ }
752
+ u() && this.scheduleBatch();
753
+ }
754
+ async handleBatchFailure(e) {
755
+ for (const t of e)
756
+ t.retries < this.maxRetries ? (t.retries++, this.queue.unshift(t), this.logger.warn(`Retry attempt ${t.retries} for payload`)) : this.logger.error("Max retries reached, discarding payload", t.payload);
757
+ u() && (this.saveQueueToStorage(), await new Promise((t) => setTimeout(t, this.retryInterval)));
758
+ }
759
+ loadQueueFromStorage() {
760
+ if (u()) {
761
+ const e = this.persistence.get("queue");
762
+ e && (this.queue = JSON.parse(e));
763
+ }
764
+ }
765
+ saveQueueToStorage() {
766
+ u() && this.persistence.set("queue", JSON.stringify(this.queue));
767
+ }
768
+ }
769
+ class de {
770
+ constructor(e) {
771
+ this.clicks = [], this.threshold = 3, this.timeWindow = 2e3, this.distanceThreshold = 30, this.client = e, this.initializeEventListener(), z(this);
772
+ }
773
+ initializeEventListener() {
774
+ document.addEventListener("click", this.handleClick.bind(this));
775
+ }
776
+ handleClick(e) {
777
+ const t = e.target;
778
+ this.shouldCaptureElement(t) && this.click(e.clientX, e.clientY, Date.now());
779
+ }
780
+ shouldCaptureElement(e) {
781
+ return !e.closest(".um-no-capture");
782
+ }
783
+ click(e, t, i) {
784
+ const n = { x: e, y: t, timestamp: i };
785
+ this.clicks.push(n), this.clicks = this.clicks.filter((r) => i - r.timestamp < this.timeWindow), this.clicks.length >= this.threshold && this.checkRageClick();
786
+ }
787
+ checkRageClick() {
788
+ const e = this.clicks[0], i = (this.clicks[this.clicks.length - 1].timestamp - e.timestamp) / 1e3;
789
+ this.clicks.every((r, o) => {
790
+ if (o === 0) return !0;
791
+ const c = this.clicks[o - 1];
792
+ return Math.sqrt(Math.pow(r.x - c.x, 2) + Math.pow(r.y - c.y, 2)) < this.distanceThreshold;
793
+ }) && this.sendRageClickEvent(i);
794
+ }
795
+ sendRageClickEvent(e) {
796
+ const t = this.clicks[this.clicks.length - 1];
797
+ document.elementFromPoint(t.x, t.y) && this.client.track("$rage_click", {
798
+ no_of_clicks: this.clicks.length,
799
+ time: e.toFixed(2)
800
+ }), this.clicks = [];
801
+ }
802
+ }
803
+ class fe {
804
+ constructor(e, t, i = h()) {
805
+ this.trackingHost = e, this.logger = i, this.config = t;
806
+ }
807
+ async send(e) {
808
+ const t = this.config.key, i = new (void 0)(this.constructUrl(t)), n = {
809
+ hostname: i.hostname,
810
+ port: 443,
811
+ path: `${i.pathname}${i.search}`,
812
+ method: "POST",
813
+ headers: {
814
+ "Content-Type": "application/json",
815
+ ...this.getCustomHeaders()
816
+ }
817
+ };
818
+ return new Promise((r, o) => {
819
+ const c = (void 0)(n, (l) => {
820
+ l.on("data", (a) => {
821
+ }), l.on("end", () => {
822
+ const a = l.statusCode || 0;
823
+ a >= 200 && a < 300 ? (this.logger.debug(`Successfully sent ${e.length} event(s)`), r()) : o(new Error(`HTTP error! status: ${a}`));
824
+ });
825
+ });
826
+ c.on("error", (l) => {
827
+ o(l);
828
+ }), c.write(JSON.stringify(e)), c.end();
829
+ });
830
+ }
831
+ constructUrl(e) {
832
+ const t = this.config.cookiePolicy !== "keep" ? `&cookie_policy=${this.config.cookiePolicy}` : "", i = this.config.ipPolicy !== "keep" ? `&ip_policy=${this.config.ipPolicy}` : "";
833
+ return `${this.trackingHost}/api/v1/s2s/event?token=${e}${t}${i}`;
834
+ }
835
+ getCustomHeaders() {
836
+ return typeof this.config.customHeaders == "function" ? this.config.customHeaders() : this.config.customHeaders ? this.config.customHeaders : {};
837
+ }
838
+ }
839
+ class m {
840
+ constructor(e, t = "all", i = {}) {
841
+ this.instance = e, this.trackingType = t, this.options = i, document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", this.initialize.bind(this)) : this.initialize();
842
+ }
843
+ initialize() {
844
+ this.trackingType !== "none" && this.setupFormTracking();
845
+ }
846
+ setupFormTracking() {
847
+ var e;
848
+ this.formElements = this.trackingType === "tagged" ? document.querySelectorAll("form[data-um-form]") : document.querySelectorAll("form"), (e = this.formElements) == null || e.forEach((t) => {
849
+ t.addEventListener("submit", this.handleFormSubmit.bind(this));
850
+ });
851
+ }
852
+ handleFormSubmit(e) {
853
+ const t = e.target, i = this._getFormDetails(t);
854
+ this.instance.track("$form", N(i)), this.options.trackFieldChanges && this.trackFieldChanges(t);
855
+ }
856
+ trackFieldChanges(e) {
857
+ e.querySelectorAll("input, select, textarea").forEach((i) => {
858
+ i.addEventListener("change", (n) => {
859
+ const r = this._getFieldProps(n.target, 0);
860
+ this.instance.track("$form_field_change", N(r));
861
+ });
862
+ });
863
+ }
864
+ static getInstance(e, t = "all", i = {}) {
865
+ return m.instance || (m.instance = new m(e, t, i)), m.instance;
866
+ }
867
+ _getFormDetails(e) {
868
+ const t = {
869
+ form_id: e.id,
870
+ form_name: e.name || "",
871
+ form_action: e.action,
872
+ form_method: e.method,
873
+ form_class: e.className,
874
+ form_attributes: this._getElementAttributes(e)
875
+ }, i = e.querySelectorAll("input, select, textarea");
876
+ return Array.from(i).filter((r) => !r.classList.contains("um-no-capture")).forEach((r, o) => {
877
+ const c = this._getFieldProps(r, o);
878
+ Object.assign(t, c);
879
+ }), t;
880
+ }
881
+ _getFieldProps(e, t) {
882
+ const i = Object.keys(e.dataset).length ? JSON.stringify(e.dataset) : void 0, n = this.getSafeText(e);
883
+ return {
884
+ [`field_${t + 1}_tag`]: e.tagName.toLowerCase(),
885
+ [`field_${t + 1}_type`]: e instanceof HTMLInputElement ? e.type : void 0,
886
+ [`field_${t + 1}_data_attributes`]: i,
887
+ [`field_${t + 1}_id`]: e.id,
888
+ [`field_${t + 1}_value`]: n,
889
+ [`field_${t + 1}_class`]: e.className,
890
+ [`field_${t + 1}_name`]: e.name,
891
+ [`field_${t + 1}_attributes`]: this._getElementAttributes(e)
892
+ };
893
+ }
894
+ _getElementAttributes(e) {
895
+ const t = {};
896
+ for (let i = 0; i < e.attributes.length; i++) {
897
+ const n = e.attributes[i];
898
+ n.name !== "value" && !n.name.startsWith("data-") && (t[n.name] = n.value);
899
+ }
900
+ return t;
901
+ }
902
+ getSafeText(e) {
903
+ let t = "";
904
+ return "value" in e && e.type !== "password" ? t = e.value : e.hasChildNodes() ? t = Array.from(e.childNodes).filter(
905
+ (n) => n.nodeType === Node.TEXT_NODE
906
+ ).map((n) => n.textContent).join("") : t = e.textContent || "", this._scrubPotentiallySensitiveValues(t);
907
+ }
908
+ _scrubPotentiallySensitiveValues(e) {
909
+ return this._shouldCaptureValue(e) ? e : "<redacted>";
910
+ }
911
+ _shouldCaptureValue(e) {
912
+ return !(this._isNullish(e) || this._isString(e) && (e = this._trim(e), /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((e || "").replace(/[- ]/g, "")) || /(^\d{3}-?\d{2}-?\d{4}$)/.test(e)));
913
+ }
914
+ _isNullish(e) {
915
+ return e == null;
916
+ }
917
+ _isString(e) {
918
+ return typeof e == "string" || e instanceof String;
919
+ }
920
+ _trim(e) {
921
+ if (typeof String.prototype.trim == "function")
922
+ return e.trim();
923
+ let t = 0, i = e.length - 1;
924
+ const n = [
925
+ " ",
926
+ `
927
+ `,
928
+ "\r",
929
+ " ",
930
+ "\f",
931
+ "\v",
932
+ " ",
933
+ " ",
934
+ " ",
935
+ " ",
936
+ " ",
937
+ " ",
938
+ " ",
939
+ " ",
940
+ " ",
941
+ " ",
942
+ " ",
943
+ " ",
944
+ " ",
945
+ "\u2028",
946
+ "\u2029",
947
+ " ",
948
+ " ",
949
+ " "
950
+ ].join("");
951
+ for (; t <= i && n.indexOf(e[t]) > -1; )
952
+ t++;
953
+ for (; i >= t && n.indexOf(e[i]) > -1; )
954
+ i--;
955
+ return e.slice(t, i + 1);
956
+ }
957
+ }
958
+ class pe {
959
+ constructor(e) {
960
+ this.config = this.mergeConfig(e, D), this.logger = h(this.config.logLevel), this.namespace = e.namespace || "usermaven", this.transport = this.initializeTransport(this.config), this.persistence = this.initializePersistence(), this.retryQueue = new I(
961
+ this.transport,
962
+ this.config.maxSendAttempts || 3,
963
+ this.config.minSendTimeout || 1e3,
964
+ 10,
965
+ 200,
966
+ // Reduced interval to .2 second
967
+ this.logger
968
+ ), u() && this.initializeBrowserFeatures(), this.anonymousId = this.getOrCreateAnonymousId(), this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`);
969
+ }
970
+ initializeBrowserFeatures() {
971
+ if (this.cookieManager = new Q(this.config.cookieDomain), this.config.autocapture && w.enabledForProject(this.config.key) && (this.autoCapture = new w(this, this.config, this.logger), this.autoCapture.init()), this.config.formTracking) {
972
+ const e = this.config.formTracking === !0 ? "all" : this.config.formTracking;
973
+ this.formTracking = m.getInstance(this, e || "none", {
974
+ trackFieldChanges: !1
975
+ });
976
+ }
977
+ this.config.autoPageview && (this.pageviewTracking = new le(this)), this.config.crossDomainLinking && this.manageCrossDomainLinking(), this.config.rageClick && (this.rageClick = new de(this)), this.setupPageLeaveTracking();
978
+ }
979
+ /**
980
+ * Recursively merge the provided configuration with the existing defaultConfig
981
+ * @param config
982
+ * @param defaultConfig
983
+ */
984
+ mergeConfig(e, t) {
985
+ const i = JSON.parse(JSON.stringify(e));
986
+ let n = { ...t, ...i };
987
+ return Object.keys(t).forEach((r) => {
988
+ k(t[r]) && (n[r] = this.mergeConfig(e[r], t[r]));
989
+ }), n;
990
+ }
991
+ init(e) {
992
+ this.config = { ...this.config, ...e }, this.logger = h(this.config.logLevel), this.namespace = e.namespace || this.namespace, this.transport = this.initializeTransport(e), this.persistence = this.initializePersistence(), this.retryQueue = new I(
993
+ this.transport,
994
+ this.config.maxSendAttempts || 3,
995
+ this.config.minSendTimeout || 1e3,
996
+ 10,
997
+ 250,
998
+ // Reduced interval to .25 second
999
+ this.logger
1000
+ ), u() && this.initializeBrowserFeatures(), this.anonymousId = this.getOrCreateAnonymousId(), this.logger.info(`Usermaven client reinitialized for namespace: ${this.namespace}`);
1001
+ }
1002
+ manageCrossDomainLinking() {
1003
+ if (!this.config.crossDomainLinking || !this.config.domains)
1004
+ return;
1005
+ const e = this.config.domains.split(",").map((i) => i.trim()), t = this.config.cookieName || `${this.namespace}_id_${this.config.key}`;
1006
+ document.addEventListener("click", (i) => {
1007
+ var c;
1008
+ const n = this.findClosestLink(i.target);
1009
+ if (!n) return;
1010
+ const r = n.getAttribute("href");
1011
+ if (!r || !r.startsWith("http")) return;
1012
+ const o = new URL(r);
1013
+ if (o.hostname !== window.location.hostname && e.includes(o.hostname)) {
1014
+ const l = (c = this.cookieManager) == null ? void 0 : c.get(t);
1015
+ l && (o.searchParams.append("_um", l), n.setAttribute("href", o.toString()));
1016
+ }
1017
+ }), this.logger.debug("Cross-domain linking initialized");
1018
+ }
1019
+ findClosestLink(e) {
1020
+ for (; e && e.tagName !== "A"; )
1021
+ e = e.parentElement;
1022
+ return e;
1023
+ }
1024
+ initializeTransport(e) {
1025
+ if (!u())
1026
+ return new fe(e.trackingHost, e);
1027
+ const t = "XMLHttpRequest" in window, i = typeof fetch < "u", n = typeof navigator < "u" && "sendBeacon" in navigator;
1028
+ if (e.useBeaconApi && n)
1029
+ return new ue(e.trackingHost, e, this.logger);
1030
+ if (e.forceUseFetch && i)
1031
+ return new U(e.trackingHost, e, this.logger);
1032
+ if (t)
1033
+ return new he(e.trackingHost, e, this.logger);
1034
+ if (i)
1035
+ return new U(e.trackingHost, e, this.logger);
1036
+ throw new Error("No suitable transport method available");
1037
+ }
1038
+ initializePersistence() {
1039
+ return this.config.disableEventPersistence || !u() ? new ge() : new V(`${this.namespace}_${this.config.key}`, this.logger);
1040
+ }
1041
+ getOrCreateAnonymousId() {
1042
+ var i, n;
1043
+ if (!u())
1044
+ return $();
1045
+ if (this.config.privacyPolicy === "strict" || this.config.cookiePolicy === "strict")
1046
+ return this.generateFingerprint();
1047
+ const e = this.config.cookieName || `${this.namespace}_id_${this.config.key}`;
1048
+ let t = (i = this.cookieManager) == null ? void 0 : i.get(e);
1049
+ if (!t) {
1050
+ if (this.config.crossDomainLinking) {
1051
+ const c = new URLSearchParams(window.location.search).get("_um"), a = window.location.hash.substring(1).split("~"), g = a.length > 1 ? a[1] : void 0;
1052
+ t = c || g || $();
1053
+ }
1054
+ t || (t = $());
1055
+ const r = 365 * 10;
1056
+ (n = this.cookieManager) == null || n.set(e, t, r, document.location.protocol !== "http:", !1);
1057
+ }
1058
+ return t;
1059
+ }
1060
+ generateFingerprint() {
1061
+ const e = navigator.userAgent, t = `${screen.width}x${screen.height}`, i = screen.colorDepth, n = Intl.DateTimeFormat().resolvedOptions().timeZone, r = `${e}|${t}|${i}|${n}`;
1062
+ return this.hashString(r);
1063
+ }
1064
+ hashString(e) {
1065
+ let t = 0;
1066
+ for (let i = 0; i < e.length; i++) {
1067
+ const n = e.charCodeAt(i);
1068
+ t = (t << 5) - t + n, t = t & t;
1069
+ }
1070
+ return t.toString(36);
1071
+ }
1072
+ async id(e, t = !1) {
1073
+ if (!k(e))
1074
+ throw new Error("User data must be an object");
1075
+ if (e.email && !ne(e.email))
1076
+ throw new Error("Invalid email provided");
1077
+ if (!e.id || !L(e.id))
1078
+ throw new Error("User ID must be a string");
1079
+ const i = e.id;
1080
+ if (this.persistence.set("userId", i), this.persistence.set("userProps", e), !t) {
1081
+ const n = {
1082
+ ...e,
1083
+ anonymous_id: this.anonymousId
1084
+ };
1085
+ await this.track("user_identify", n);
1086
+ }
1087
+ this.logger.info("User identified:", e);
1088
+ }
1089
+ track(e, t, i = !1) {
1090
+ this.trackInternal(e, t, i);
1091
+ }
1092
+ trackInternal(e, t, i = !1) {
1093
+ if (!L(e))
1094
+ throw new Error("Event name must be a string");
1095
+ if (t !== void 0 && (typeof t != "object" || t === null || Array.isArray(t)))
1096
+ throw new Error("Event payload must be a non-null object and not an array");
1097
+ const n = this.createEventPayload(e, t);
1098
+ try {
1099
+ if (i) {
1100
+ this.transport.send(n), this.logger.debug(`Event sent: ${e}`, [n]);
1101
+ return;
1102
+ }
1103
+ this.retryQueue.add(n), this.logger.debug(`Event tracked: ${e}`, [n]);
1104
+ } catch (r) {
1105
+ throw this.logger.error(`Failed to track event: ${e}`, r), new Error(`Failed to track event: ${e}`);
1106
+ }
1107
+ }
1108
+ rawTrack(e) {
1109
+ if (!k(e))
1110
+ throw new Error("Event payload must be an object");
1111
+ this.track("raw", e);
1112
+ }
1113
+ async group(e, t = !1) {
1114
+ if (!k(e))
1115
+ throw new Error("Company properties must be an object");
1116
+ if (!e.id || !e.name || !e.created_at)
1117
+ throw new Error("Company properties must include id, name, and created_at");
1118
+ this.persistence.set("companyProps", e), t || await this.track("group", e), this.logger.info("Company identified:", e);
1119
+ }
1120
+ createEventPayload(e, t) {
1121
+ const i = this.persistence.get("userProps") || {}, n = this.persistence.get("companyProps") || void 0, r = this.persistence.get("userId"), o = this.persistence.get("global_props") || {}, c = this.persistence.get(`props_${e}`) || {};
1122
+ let l = t || {};
1123
+ const a = {
1124
+ event_id: "",
1125
+ user: {
1126
+ anonymous_id: this.anonymousId,
1127
+ id: r,
1128
+ ...i
1129
+ },
1130
+ ...n && { company: n },
1131
+ ids: this.getThirdPartyIds(),
1132
+ utc_time: (/* @__PURE__ */ new Date()).toISOString(),
1133
+ local_tz_offset: (/* @__PURE__ */ new Date()).getTimezoneOffset(),
1134
+ api_key: this.config.key,
1135
+ src: "usermaven",
1136
+ event_type: e,
1137
+ namespace: this.namespace,
1138
+ ...o,
1139
+ ...c
1140
+ };
1141
+ if (e === "$autocapture") {
1142
+ const g = this.processAutocaptureAttributes(t || {});
1143
+ a.autocapture_attributes = g;
1144
+ } else
1145
+ Array.isArray(this.config.propertyBlacklist) && this.config.propertyBlacklist.forEach((g) => {
1146
+ delete l[g];
1147
+ }), a.event_attributes = l;
1148
+ return u() && (a.referer = document.referrer, a.url = window.location.href, a.page_title = document.title, a.doc_path = window.location.pathname, a.doc_host = window.location.hostname, a.doc_search = window.location.search, a.screen_resolution = `${window.screen.width}x${window.screen.height}`, a.vp_size = `${window.innerWidth}x${window.innerHeight}`, a.user_agent = navigator.userAgent, a.user_language = navigator.language, a.doc_encoding = document.characterSet, a.utm = this.getUtmParams()), a;
1149
+ }
1150
+ processAutocaptureAttributes(e) {
1151
+ let t = {};
1152
+ const i = e.$elements || [];
1153
+ return i.length && (t = { ...i[0] }), t.el_text = t.$el_text || "", t.event_type = e.$event_type || "", ["$ce_version", "$event_type", "$initial_referrer", "$initial_referring_domain", "$referrer", "$referring_domain", "$elements"].forEach((n) => {
1154
+ delete t[n];
1155
+ }), delete t.$el_text, delete t.nth_child, delete t.nth_of_type, t;
1156
+ }
1157
+ getCookie(e) {
1158
+ var t;
1159
+ return ((t = this.cookieManager) == null ? void 0 : t.get(e)) || null;
1160
+ }
1161
+ getThirdPartyIds() {
1162
+ const e = {};
1163
+ if (u()) {
1164
+ const t = this.getCookie("_fbp");
1165
+ t && (e.fbp = t);
1166
+ }
1167
+ return e;
1168
+ }
1169
+ getUtmParams() {
1170
+ const e = {}, t = oe(window.location.search);
1171
+ return ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"].forEach((n) => {
1172
+ t[n] && (e[n.replace("utm_", "")] = t[n]);
1173
+ }), e;
1174
+ }
1175
+ pageview() {
1176
+ u() ? this.track("pageview", {
1177
+ url: window.location.href,
1178
+ referrer: document.referrer,
1179
+ title: document.title
1180
+ }, !0) : this.logger.warn("Pageview tracking is not available in server-side environments");
1181
+ }
1182
+ setupPageLeaveTracking() {
1183
+ if (!u()) return;
1184
+ let e = !1, t = !1;
1185
+ const i = () => {
1186
+ !e && !t && (e = !0, this.track("$pageleave", {
1187
+ url: window.location.href,
1188
+ referrer: document.referrer,
1189
+ title: document.title
1190
+ }));
1191
+ };
1192
+ window.addEventListener("beforeunload", (r) => {
1193
+ t = !0, setTimeout(() => {
1194
+ t = !1;
1195
+ }, 100);
1196
+ }), document.addEventListener("visibilitychange", () => {
1197
+ document.visibilityState === "hidden" && !t && i();
1198
+ });
1199
+ const n = history.pushState;
1200
+ history.pushState = function() {
1201
+ return i(), n.apply(this, arguments);
1202
+ }, window.addEventListener("popstate", i);
1203
+ }
1204
+ getConfig() {
1205
+ return this.config;
1206
+ }
1207
+ getLogger() {
1208
+ return this.logger;
1209
+ }
1210
+ async reset(e = !1) {
1211
+ if (this.persistence.clear(), e && this.cookieManager) {
1212
+ const t = this.config.cookieName || `${this.namespace}_id_${this.config.key}`;
1213
+ this.cookieManager.delete(t), this.anonymousId = this.getOrCreateAnonymousId();
1214
+ }
1215
+ this.logger.info("core state reset", { resetAnonId: e, namespace: this.namespace });
1216
+ }
1217
+ set(e, t) {
1218
+ if (!k(e))
1219
+ throw new Error("Properties must be an object");
1220
+ const i = t == null ? void 0 : t.eventType, n = (t == null ? void 0 : t.persist) ?? !0;
1221
+ if (i) {
1222
+ let r = this.persistence.get(`props_${i}`) || {};
1223
+ r = { ...r, ...e }, this.persistence.set(`props_${i}`, r);
1224
+ } else {
1225
+ let r = this.persistence.get("global_props") || {};
1226
+ r = { ...r, ...e }, this.persistence.set("global_props", r);
1227
+ }
1228
+ n && this.persistence.save(), this.logger.debug("Properties set", {
1229
+ properties: e,
1230
+ eventType: i || "global",
1231
+ persist: n
1232
+ });
1233
+ }
1234
+ setUserId(e) {
1235
+ this.persistence.set("userId", e);
1236
+ let t = this.persistence.get("userProps") || {};
1237
+ t.id = e, this.persistence.set("userProps", t), this.persistence.save();
1238
+ }
1239
+ unset(e, t) {
1240
+ const i = t == null ? void 0 : t.eventType, n = (t == null ? void 0 : t.persist) ?? !0;
1241
+ if (i) {
1242
+ let r = this.persistence.get(`props_${i}`) || {};
1243
+ delete r[e], this.persistence.set(`props_${i}`, r);
1244
+ } else {
1245
+ let r = this.persistence.get("global_props") || {};
1246
+ delete r[e], this.persistence.set("global_props", r);
1247
+ }
1248
+ n && this.persistence.save(), this.logger.debug(`Property unset: ${e}`, `Event type: ${i || "global"}`);
1249
+ }
1250
+ }
1251
+ function me(s) {
1252
+ const e = JSON.parse(JSON.stringify(s)), t = C(e), i = { ...D, ...t };
1253
+ if (!i.key)
1254
+ throw new Error("API key is required!");
1255
+ if (!i.trackingHost)
1256
+ throw new Error("Tracking host is required!");
1257
+ return new pe(i);
1258
+ }
1259
+ function ye(s) {
1260
+ var n;
1261
+ const e = {
1262
+ key: s.getAttribute("data-key") || void 0,
1263
+ trackingHost: s.getAttribute("data-tracking-host") || "https://events.usermaven.com",
1264
+ logLevel: ae(s.getAttribute("data-log-level")),
1265
+ autocapture: s.getAttribute("data-autocapture") === "true",
1266
+ formTracking: s.getAttribute("data-form-tracking") === "true" ? "all" : !1,
1267
+ autoPageview: s.getAttribute("data-auto-pageview") === "true",
1268
+ useBeaconApi: s.getAttribute("data-use-beacon-api") === "true",
1269
+ forceUseFetch: s.getAttribute("data-force-use-fetch") === "true",
1270
+ gaHook: s.getAttribute("data-ga-hook") === "true",
1271
+ segmentHook: s.getAttribute("data-segment-hook") === "true",
1272
+ randomizeUrl: s.getAttribute("data-randomize-url") === "true",
1273
+ capture3rdPartyCookies: s.getAttribute("data-capture-3rd-party-cookies") === "false" ? !1 : void 0,
1274
+ idMethod: s.getAttribute("data-id-method") || void 0,
1275
+ privacyPolicy: s.getAttribute("data-privacy-policy") === "strict" ? "strict" : void 0,
1276
+ ipPolicy: s.getAttribute("data-ip-policy") || void 0,
1277
+ cookiePolicy: s.getAttribute("data-cookie-policy") || void 0,
1278
+ minSendTimeout: parseInt(s.getAttribute("data-min-send-timeout") || "", 10) || void 0,
1279
+ maxSendTimeout: parseInt(s.getAttribute("data-max-send-timeout") || "", 10) || void 0,
1280
+ maxSendAttempts: parseInt(s.getAttribute("data-max-send-attempts") || "", 10) || void 0,
1281
+ propertiesStringMaxLength: parseInt(s.getAttribute("data-properties-string-max-length") || "", 10) || null,
1282
+ propertyBlacklist: ((n = s.getAttribute("data-property-blacklist")) == null ? void 0 : n.split(",")) || void 0,
1283
+ exclude: s.getAttribute("data-exclude") || void 0,
1284
+ namespace: s.getAttribute("data-namespace") || void 0,
1285
+ crossDomainLinking: s.getAttribute("data-cross-domain-linking") !== "false",
1286
+ domains: s.getAttribute("data-domains") || void 0,
1287
+ maskAllText: s.getAttribute("data-mask-all-text") === "true",
1288
+ maskAllElementAttributes: s.getAttribute("data-mask-all-element-attributes") === "true"
1289
+ }, t = me(e), i = e.namespace || "usermaven";
1290
+ u() && t.pageview(), we(i, t);
1291
+ }
1292
+ function we(s, e) {
1293
+ let t = !1;
1294
+ const i = [], n = [];
1295
+ function r() {
1296
+ for (; i.length > 0; ) {
1297
+ const a = i.shift();
1298
+ a && window[s].apply(null, a);
1299
+ }
1300
+ }
1301
+ function o() {
1302
+ n.forEach((a) => a()), n.length = 0;
1303
+ }
1304
+ window[s] = function(...a) {
1305
+ const g = a[0];
1306
+ if (g === "onLoad") {
1307
+ typeof a[1] == "function" && (t ? a[1]() : n.push(a[1]));
1308
+ return;
1309
+ }
1310
+ if (!t) {
1311
+ i.push(a);
1312
+ return;
1313
+ }
1314
+ if (typeof e[g] == "function")
1315
+ return e[g].apply(e, a.slice(1));
1316
+ console.error(`Method ${g} not found on UsermavenClient`);
1317
+ };
1318
+ const c = `${s}Q`, l = window[c] || [];
1319
+ for (window[c] = l, l.push = function(...a) {
1320
+ return window[s].apply(null, a), Array.prototype.push.apply(this, a);
1321
+ }, setTimeout(() => {
1322
+ t = !0, r(), o(), console.log(`Usermaven client for namespace ${s} is ready`);
1323
+ }, 0); l.length > 0; ) {
1324
+ const a = l.shift();
1325
+ a && i.push(a);
1326
+ }
1327
+ }
1328
+ u() && function(s, e) {
1329
+ const t = s.currentScript;
1330
+ function i() {
1331
+ t && t.src.includes("lib.js") && ye(t);
1332
+ }
1333
+ typeof e < "u" && (s.readyState === "loading" ? s.addEventListener("DOMContentLoaded", i) : i());
1334
+ }(document, window);
1335
+
1336
+ function createClient(params) {
1337
+ return me(params);
1338
+ }
1339
+
1340
+ function useUsermaven() {
1341
+ const client = useContext(UsermavenContext);
1342
+ if (!client) {
1343
+ throw new Error("Before calling useUsermaven() hook, please wrap your component into <UsermavenProvider />. Read more in http://jitsu.com/docs/sending-data/js-sdk/react");
1344
+ }
1345
+ const id = useCallback((userData, doNotSendEvent) => client === null || client === void 0 ? void 0 : client.id(userData, doNotSendEvent), [client]);
1346
+ const trackPageView = useCallback(() => client === null || client === void 0 ? void 0 : client.track('pageview'), [client]);
1347
+ const track = useCallback((typeName, payload) => client === null || client === void 0 ? void 0 : client.track(typeName, payload), [client]);
1348
+ const rawTrack = useCallback((payload) => client === null || client === void 0 ? void 0 : client.rawTrack(payload), [client]);
1349
+ const set = useCallback((properties, opts) => client === null || client === void 0 ? void 0 : client.set(properties, opts), [client]);
1350
+ const unset = useCallback((propertyName, opts) => client === null || client === void 0 ? void 0 : client.unset(propertyName, opts), [client]);
1351
+ return Object.assign(Object.assign({}, client), { id,
1352
+ track,
1353
+ trackPageView,
1354
+ rawTrack,
1355
+ set,
1356
+ unset });
1357
+ }
1358
+
1359
+ function useUrlChange() {
1360
+ const [url, setUrl] = useState('');
1361
+ useEffect(() => {
1362
+ setUrl(window.location.href);
1363
+ const handleUrlChange = () => {
1364
+ setUrl(window.location.href);
1365
+ };
1366
+ window.addEventListener('popstate', handleUrlChange);
1367
+ const originalPushState = window.history.pushState;
1368
+ const originalReplaceState = window.history.replaceState;
1369
+ window.history.pushState = function () {
1370
+ originalPushState.apply(this, arguments);
1371
+ handleUrlChange();
1372
+ };
1373
+ window.history.replaceState = function () {
1374
+ originalReplaceState.apply(this, arguments);
1375
+ handleUrlChange();
1376
+ };
1377
+ return () => {
1378
+ window.removeEventListener('popstate', handleUrlChange);
1379
+ window.history.pushState = originalPushState;
1380
+ window.history.replaceState = originalReplaceState;
1381
+ };
1382
+ }, []);
1383
+ return url;
1384
+ }
1385
+ function usePageView(usermaven, opts = {}) {
1386
+ const url = useUrlChange();
1387
+ const trackPageView = useCallback(() => {
1388
+ if (typeof window === 'undefined') {
1389
+ return;
1390
+ }
1391
+ if (opts.before) {
1392
+ opts.before(usermaven);
1393
+ }
1394
+ usermaven.track((opts === null || opts === void 0 ? void 0 : opts.typeName) || 'pageview', Object.assign(Object.assign({}, opts.payload), { url: window.location.href, path: window.location.pathname, referrer: document.referrer, title: document.title }));
1395
+ }, [usermaven, opts.before, opts.typeName, opts.payload]);
1396
+ useEffect(() => {
1397
+ if (url) {
1398
+ trackPageView();
1399
+ }
1400
+ }, [url, trackPageView]);
1401
+ return usermaven;
1402
+ }
1403
+
1404
+ /*!
1405
+ * cookie
1406
+ * Copyright(c) 2012-2014 Roman Shtylman
1407
+ * Copyright(c) 2015 Douglas Christopher Wilson
1408
+ * MIT Licensed
1409
+ */
1410
+ var serialize_1 = serialize;
1411
+
1412
+ /**
1413
+ * Module variables.
1414
+ * @private
1415
+ */
1416
+
1417
+ var __toString = Object.prototype.toString;
1418
+
1419
+ /**
1420
+ * RegExp to match field-content in RFC 7230 sec 3.2
1421
+ *
1422
+ * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
1423
+ * field-vchar = VCHAR / obs-text
1424
+ * obs-text = %x80-FF
1425
+ */
1426
+
1427
+ var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
1428
+
1429
+ /**
1430
+ * Serialize data into a cookie header.
1431
+ *
1432
+ * Serialize the a name value pair into a cookie string suitable for
1433
+ * http headers. An optional options object specified cookie parameters.
1434
+ *
1435
+ * serialize('foo', 'bar', { httpOnly: true })
1436
+ * => "foo=bar; httpOnly"
1437
+ *
1438
+ * @param {string} name
1439
+ * @param {string} val
1440
+ * @param {object} [options]
1441
+ * @return {string}
1442
+ * @public
1443
+ */
1444
+
1445
+ function serialize(name, val, options) {
1446
+ var opt = options || {};
1447
+ var enc = opt.encode || encode;
1448
+
1449
+ if (typeof enc !== 'function') {
1450
+ throw new TypeError('option encode is invalid');
1451
+ }
1452
+
1453
+ if (!fieldContentRegExp.test(name)) {
1454
+ throw new TypeError('argument name is invalid');
1455
+ }
1456
+
1457
+ var value = enc(val);
1458
+
1459
+ if (value && !fieldContentRegExp.test(value)) {
1460
+ throw new TypeError('argument val is invalid');
1461
+ }
1462
+
1463
+ var str = name + '=' + value;
1464
+
1465
+ if (null != opt.maxAge) {
1466
+ var maxAge = opt.maxAge - 0;
1467
+
1468
+ if (isNaN(maxAge) || !isFinite(maxAge)) {
1469
+ throw new TypeError('option maxAge is invalid')
1470
+ }
1471
+
1472
+ str += '; Max-Age=' + Math.floor(maxAge);
1473
+ }
1474
+
1475
+ if (opt.domain) {
1476
+ if (!fieldContentRegExp.test(opt.domain)) {
1477
+ throw new TypeError('option domain is invalid');
1478
+ }
1479
+
1480
+ str += '; Domain=' + opt.domain;
1481
+ }
1482
+
1483
+ if (opt.path) {
1484
+ if (!fieldContentRegExp.test(opt.path)) {
1485
+ throw new TypeError('option path is invalid');
1486
+ }
1487
+
1488
+ str += '; Path=' + opt.path;
1489
+ }
1490
+
1491
+ if (opt.expires) {
1492
+ var expires = opt.expires;
1493
+
1494
+ if (!isDate(expires) || isNaN(expires.valueOf())) {
1495
+ throw new TypeError('option expires is invalid');
1496
+ }
1497
+
1498
+ str += '; Expires=' + expires.toUTCString();
1499
+ }
1500
+
1501
+ if (opt.httpOnly) {
1502
+ str += '; HttpOnly';
1503
+ }
1504
+
1505
+ if (opt.secure) {
1506
+ str += '; Secure';
1507
+ }
1508
+
1509
+ if (opt.priority) {
1510
+ var priority = typeof opt.priority === 'string'
1511
+ ? opt.priority.toLowerCase()
1512
+ : opt.priority;
1513
+
1514
+ switch (priority) {
1515
+ case 'low':
1516
+ str += '; Priority=Low';
1517
+ break
1518
+ case 'medium':
1519
+ str += '; Priority=Medium';
1520
+ break
1521
+ case 'high':
1522
+ str += '; Priority=High';
1523
+ break
1524
+ default:
1525
+ throw new TypeError('option priority is invalid')
1526
+ }
1527
+ }
1528
+
1529
+ if (opt.sameSite) {
1530
+ var sameSite = typeof opt.sameSite === 'string'
1531
+ ? opt.sameSite.toLowerCase() : opt.sameSite;
1532
+
1533
+ switch (sameSite) {
1534
+ case true:
1535
+ str += '; SameSite=Strict';
1536
+ break;
1537
+ case 'lax':
1538
+ str += '; SameSite=Lax';
1539
+ break;
1540
+ case 'strict':
1541
+ str += '; SameSite=Strict';
1542
+ break;
1543
+ case 'none':
1544
+ str += '; SameSite=None';
1545
+ break;
1546
+ default:
1547
+ throw new TypeError('option sameSite is invalid');
1548
+ }
1549
+ }
1550
+
1551
+ return str;
1552
+ }
1553
+
1554
+ /**
1555
+ * URL-encode value.
1556
+ *
1557
+ * @param {string} str
1558
+ * @returns {string}
1559
+ */
1560
+
1561
+ function encode (val) {
1562
+ return encodeURIComponent(val)
1563
+ }
1564
+
1565
+ /**
1566
+ * Determine if value is a Date.
1567
+ *
1568
+ * @param {*} val
1569
+ * @private
1570
+ */
1571
+
1572
+ function isDate (val) {
1573
+ return __toString.call(val) === '[object Date]' ||
1574
+ val instanceof Date
1575
+ }
1576
+
1577
+ function middlewareEnv(req, res, opts = {}) {
1578
+ return {
1579
+ getAnonymousId({ name, domain }) {
1580
+ if (opts === null || opts === void 0 ? void 0 : opts.disableCookies) {
1581
+ return "";
1582
+ }
1583
+ const cookie = req.cookies[name];
1584
+ if (cookie) {
1585
+ return cookie;
1586
+ }
1587
+ const cookieOpts = {
1588
+ maxAge: 31622400 * 10,
1589
+ httpOnly: false,
1590
+ };
1591
+ if (domain) {
1592
+ cookieOpts.domain = domain;
1593
+ }
1594
+ let newId = Math.random().toString(36).substring(2, 12);
1595
+ res.headers.set("Set-Cookie", serialize_1(name, newId, cookieOpts));
1596
+ return newId;
1597
+ },
1598
+ getSourceIp() {
1599
+ let ip = req.headers.get("x-forwarded-for") || req.headers.get("x-real-ip") || req.ip;
1600
+ return ip && ip.split(",")[0].trim();
1601
+ },
1602
+ describeClient() {
1603
+ var _a;
1604
+ const requestHost = req.headers.get("x-forwarded-host") || req.headers.get("host") || req.nextUrl.hostname;
1605
+ const proto = req.headers.get("x-forwarded-proto") || ((_a = req.nextUrl.protocol) === null || _a === void 0 ? void 0 : _a.replace(":", ""));
1606
+ let query = req.nextUrl.search;
1607
+ let path = req.nextUrl.pathname;
1608
+ return {
1609
+ doc_encoding: "",
1610
+ doc_host: requestHost,
1611
+ doc_path: req.url,
1612
+ doc_search: query,
1613
+ page_title: "",
1614
+ referer: req.headers.get("referrer"),
1615
+ screen_resolution: "",
1616
+ url: `${proto}://${requestHost}${path || ""}${query || ""}`,
1617
+ user_agent: req.headers.get("user-agent"),
1618
+ user_language: req.headers.get("accept-language") && req.headers.get("accept-language").split(",")[0],
1619
+ vp_size: "",
1620
+ };
1621
+ },
1622
+ };
1623
+ }
1624
+
1625
+ export { UsermavenContext, UsermavenProvider, createClient, middlewareEnv, usePageView, useUsermaven };