@usermaven/nextjs 1.2.5

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,2627 @@
1
+ import * as React from 'react';
2
+ import { createContext, useContext, useCallback, useEffect } from 'react';
3
+ import { useRouter } from 'next/router';
4
+
5
+ const UsermavenContext = createContext(null);
6
+
7
+ const JitsuProvider = function ({ children, client }) {
8
+ const Context = UsermavenContext;
9
+ return React.createElement(Context.Provider, { value: client }, children);
10
+ };
11
+
12
+ /******************************************************************************
13
+ Copyright (c) Microsoft Corporation.
14
+
15
+ Permission to use, copy, modify, and/or distribute this software for any
16
+ purpose with or without fee is hereby granted.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
19
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
20
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
21
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
22
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
23
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
24
+ PERFORMANCE OF THIS SOFTWARE.
25
+ ***************************************************************************** */
26
+
27
+ var __assign = function() {
28
+ __assign = Object.assign || function __assign(t) {
29
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
30
+ s = arguments[i];
31
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
32
+ }
33
+ return t;
34
+ };
35
+ return __assign.apply(this, arguments);
36
+ };
37
+
38
+ function __rest(s, e) {
39
+ var t = {};
40
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
41
+ t[p] = s[p];
42
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
43
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
44
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
45
+ t[p[i]] = s[p[i]];
46
+ }
47
+ return t;
48
+ }
49
+
50
+ function __awaiter(thisArg, _arguments, P, generator) {
51
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
52
+ return new (P || (P = Promise))(function (resolve, reject) {
53
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
54
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
55
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
56
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
57
+ });
58
+ }
59
+
60
+ function __generator(thisArg, body) {
61
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
62
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
63
+ function verb(n) { return function (v) { return step([n, v]); }; }
64
+ function step(op) {
65
+ if (f) throw new TypeError("Generator is already executing.");
66
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
67
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
68
+ if (y = 0, t) op = [op[0] & 2, t.value];
69
+ switch (op[0]) {
70
+ case 0: case 1: t = op; break;
71
+ case 4: _.label++; return { value: op[1], done: false };
72
+ case 5: _.label++; y = op[1]; op = [0]; continue;
73
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
74
+ default:
75
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
76
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
77
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
78
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
79
+ if (t[2]) _.ops.pop();
80
+ _.trys.pop(); continue;
81
+ }
82
+ op = body.call(thisArg, _);
83
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
84
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
85
+ }
86
+ }
87
+
88
+ function __spreadArray(to, from, pack) {
89
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
90
+ if (ar || !(i in from)) {
91
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
92
+ ar[i] = from[i];
93
+ }
94
+ }
95
+ return to.concat(ar || Array.prototype.slice.call(from));
96
+ }
97
+
98
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
99
+ var e = new Error(message);
100
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
101
+ };
102
+
103
+ var LogLevels = {
104
+ DEBUG: { name: "DEBUG", severity: 10 },
105
+ INFO: { name: "INFO", severity: 100 },
106
+ WARN: { name: "WARN", severity: 1000 },
107
+ ERROR: { name: "ERROR", severity: 10000 },
108
+ NONE: { name: "NONE", severity: 10000 }
109
+ };
110
+ var rootLogger = null;
111
+ /**
112
+ * Create logger or return cached instance
113
+ */
114
+ function getLogger() {
115
+ if (rootLogger) {
116
+ return rootLogger;
117
+ }
118
+ else {
119
+ return rootLogger = createLogger();
120
+ }
121
+ }
122
+ function setRootLogLevel(logLevelName) {
123
+ var logLevel = LogLevels[logLevelName.toLocaleUpperCase()];
124
+ if (!logLevel) {
125
+ console.warn("Can't find log level with name ".concat(logLevelName.toLocaleUpperCase(), ", defaulting to INFO"));
126
+ logLevel = LogLevels.INFO;
127
+ }
128
+ rootLogger = createLogger(logLevel);
129
+ return rootLogger;
130
+ }
131
+ function setDebugVar(name, val) {
132
+ if (!isWindowAvailable()) {
133
+ return;
134
+ }
135
+ var win = window;
136
+ if (!win.__usermavenDebug) {
137
+ win.__usermavenDebug = {};
138
+ }
139
+ win.__usermavenDebug[name] = val;
140
+ }
141
+ /**
142
+ * Creates a loggger with given log-level
143
+ * @param logLevel
144
+ */
145
+ function createLogger(logLevel) {
146
+ var globalLogLevel = isWindowAvailable() && window['__eventNLogLevel'];
147
+ var minLogLevel = LogLevels.WARN;
148
+ if (globalLogLevel) {
149
+ var level = LogLevels[globalLogLevel.toUpperCase()];
150
+ if (level && level > 0) {
151
+ minLogLevel = level;
152
+ }
153
+ }
154
+ else if (logLevel) {
155
+ minLogLevel = logLevel;
156
+ }
157
+ var logger = { minLogLevel: minLogLevel };
158
+ Object.values(LogLevels).forEach(function (_a) {
159
+ var name = _a.name, severity = _a.severity;
160
+ logger[name.toLowerCase()] = function () {
161
+ var args = [];
162
+ for (var _i = 0; _i < arguments.length; _i++) {
163
+ args[_i] = arguments[_i];
164
+ }
165
+ if (severity >= minLogLevel.severity && args.length > 0) {
166
+ var message = args[0];
167
+ var msgArgs = args.splice(1);
168
+ var msgFormatted = "[J-".concat(name, "] ").concat(message);
169
+ if (name === 'DEBUG' || name === 'INFO') {
170
+ console.log.apply(console, __spreadArray([msgFormatted], msgArgs, false));
171
+ }
172
+ else if (name === 'WARN') {
173
+ console.warn.apply(console, __spreadArray([msgFormatted], msgArgs, false));
174
+ }
175
+ else {
176
+ console.error.apply(console, __spreadArray([msgFormatted], msgArgs, false));
177
+ }
178
+ }
179
+ };
180
+ });
181
+ setDebugVar("logger", logger);
182
+ return logger;
183
+ }
184
+
185
+ /**
186
+ * Checks if global variable 'window' is available. If it's available,
187
+ * code runs in browser environment
188
+ */
189
+
190
+ function isWindowAvailable(warnMsg = undefined) {
191
+ //here we check not only of window object is globally available, but also if it's not a fake one
192
+ //react-native do have a window object, but it's not a real one: https://stackoverflow.com/questions/49911424/what-does-the-variable-window-represent-in-react-native
193
+ const windowAvailable = !!globalThis.window && !!globalThis.window.document && !!globalThis.window.location;
194
+
195
+ if (!windowAvailable && warnMsg) {
196
+ getLogger().warn(warnMsg);
197
+ }
198
+ return windowAvailable;
199
+ }
200
+
201
+
202
+ /**
203
+ * @param msg
204
+ * @return {Window}
205
+ */
206
+ function requireWindow(msg = undefined) {
207
+ if (!isWindowAvailable()) {
208
+ throw new Error(msg || "window' is not available. Seems like this code runs outside browser environment. It shouldn't happen")
209
+ }
210
+ return window;
211
+ }
212
+
213
+ // Note: updated this method to test on staging (Ref:: https://github.com/PostHog/posthog-js/blob/master/src/storage.ts#L42)
214
+ // Commented out some jitsu cookies setters that are not bring used in posthog-js
215
+ function serializeCookie(name, val, opt) {
216
+ if (opt === void 0) { opt = {}; }
217
+ try {
218
+ var maxAge = opt.maxAge, domain = opt.domain, path = opt.path, expires = opt.expires, httpOnly = opt.httpOnly, secure = opt.secure, sameSite = opt.sameSite;
219
+ var new_cookie_val = "".concat(name, "=").concat(encodeURIComponent(val));
220
+ if (domain) {
221
+ new_cookie_val += "; domain=".concat(domain);
222
+ }
223
+ if (path) {
224
+ new_cookie_val += "; path=".concat(path);
225
+ }
226
+ else {
227
+ new_cookie_val += "; path=/";
228
+ }
229
+ if (expires) {
230
+ new_cookie_val += "; expires=".concat(expires.toUTCString());
231
+ }
232
+ if (maxAge) {
233
+ new_cookie_val += "; max-age=".concat(maxAge);
234
+ }
235
+ if (httpOnly) {
236
+ new_cookie_val += "; httponly";
237
+ }
238
+ if (secure) {
239
+ new_cookie_val += "; secure";
240
+ }
241
+ if (sameSite) {
242
+ var sameSiteAttr = typeof sameSite === "string"
243
+ ? sameSite.toLowerCase()
244
+ : sameSite;
245
+ switch (sameSiteAttr) {
246
+ case true:
247
+ new_cookie_val += "; SameSite=Strict";
248
+ break;
249
+ case "lax":
250
+ new_cookie_val += "; SameSite=Lax";
251
+ break;
252
+ case "strict":
253
+ new_cookie_val += "; SameSite=Strict";
254
+ break;
255
+ case "none":
256
+ new_cookie_val += "; SameSite=None";
257
+ break;
258
+ }
259
+ }
260
+ else if (secure) {
261
+ /**
262
+ * SameSite=None - means that the browser sends the cookie with both cross-site and same-site requests.
263
+ * The Secure attribute must also be set when setting this value, like so SameSite=None; Secure.
264
+ * If Secure is missing an error will be logged.
265
+ *
266
+ * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
267
+ */
268
+ new_cookie_val += "; SameSite=None";
269
+ }
270
+ return new_cookie_val;
271
+ }
272
+ catch (e) {
273
+ getLogger().error("serializeCookie", e);
274
+ return '';
275
+ }
276
+ }
277
+
278
+ // Courtesy: https://stackoverflow.com/a/23945027
279
+ function extractHostname(url) {
280
+ var hostname;
281
+ //find & remove protocol (http, ftp, etc.) and get hostname
282
+ if (url.indexOf("//") > -1) {
283
+ hostname = url.split('/')[2];
284
+ }
285
+ else {
286
+ hostname = url.split('/')[0];
287
+ }
288
+ //find & remove port number
289
+ hostname = hostname.split(':')[0];
290
+ //find & remove "?"
291
+ hostname = hostname.split('?')[0];
292
+ return hostname;
293
+ }
294
+ // Warning: you can use this function to extract the "root" domain, but it will not be as accurate as using the psl package.
295
+ // https://www.npmjs.com/package/psl
296
+ var extractRootDomain = function (url) {
297
+ var domain = extractHostname(url), splitArr = domain.split('.'), arrLen = splitArr.length;
298
+ // extracting the root domain here
299
+ // if there is a subdomain
300
+ if (arrLen > 2) {
301
+ if (splitArr[arrLen - 1].length == 2) {
302
+ // likely a ccTLD
303
+ domain = splitArr[arrLen - 2] + '.' + splitArr[arrLen - 1];
304
+ // if the second level domain is also two letters (like co.uk), include the next part up
305
+ if (splitArr[arrLen - 2].length == 2) {
306
+ domain = splitArr[arrLen - 3] + '.' + domain;
307
+ }
308
+ }
309
+ else {
310
+ // likely a gTLD
311
+ domain = splitArr[arrLen - 2] + '.' + splitArr[arrLen - 1];
312
+ }
313
+ }
314
+ return domain;
315
+ };
316
+ var extractTopLevelDomain = function (url) {
317
+ var DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i;
318
+ var matches = url.match(DOMAIN_MATCH_REGEX), domain = matches ? matches[0] : '';
319
+ return domain;
320
+ };
321
+ var extractRoot = function (url) {
322
+ var domainParts = url.split(".");
323
+ var domainLength = domainParts.length;
324
+ // Check if it's an IP address
325
+ if (domainLength === 4 && domainParts.every(function (part) { return !isNaN(part); })) {
326
+ return url;
327
+ }
328
+ var rootDomain = extractTopLevelDomain(url);
329
+ if (!rootDomain) { // If it's not a top level domain, use a fallback method
330
+ rootDomain = extractRootDomain(url);
331
+ }
332
+ return rootDomain;
333
+ };
334
+ var getCookieDomain = function () {
335
+ if (isWindowAvailable()) {
336
+ // const domain = window.location.hostname.replace("www.", "")
337
+ //
338
+ // // Check if subdomain is set, if yes, we remove the subdomain from the cookie domain and return the root domain with a leading dot
339
+ // // This is to ensure that cookies are set correctly for cross domain tracking
340
+ // const subdomain = domain.split('.')[0]
341
+ // if (subdomain) {
342
+ // return '.' + extractRootDomain(domain)
343
+ // }
344
+ return extractRoot(window.location.hostname);
345
+ }
346
+ return undefined;
347
+ };
348
+ var cookieParsingCache;
349
+ function parseCookieString(cookieStr) {
350
+ if (!cookieStr) {
351
+ return {};
352
+ }
353
+ var res = {};
354
+ var cookies = cookieStr.split(";");
355
+ for (var i = 0; i < cookies.length; i++) {
356
+ var cookie = cookies[i];
357
+ var idx = cookie.indexOf("=");
358
+ if (idx > 0) {
359
+ res[cookie.substr(i > 0 ? 1 : 0, i > 0 ? idx - 1 : idx)] = cookie.substr(idx + 1);
360
+ }
361
+ }
362
+ return res;
363
+ }
364
+ function copyAttributes(source, target) {
365
+ return Array.from(source.attributes).forEach(function (attribute) {
366
+ target.setAttribute(attribute.nodeName, attribute.nodeValue);
367
+ });
368
+ }
369
+ function insertAndExecute(element, html) {
370
+ element.innerHTML = html;
371
+ var scripts = element.getElementsByTagName("script");
372
+ var index;
373
+ for (index = scripts.length - 1; index >= 0; index--) {
374
+ var script = scripts[index];
375
+ var tag = document.createElement("script");
376
+ copyAttributes(script, tag);
377
+ if (script.innerHTML) {
378
+ tag.innerHTML = script.innerHTML;
379
+ }
380
+ tag.setAttribute("data-usermaven-tag-id", element.id);
381
+ document.getElementsByTagName("head")[0].appendChild(tag);
382
+ scripts[index].parentNode.removeChild(scripts[index]);
383
+ }
384
+ }
385
+ var getCookies = function (useCache) {
386
+ if (useCache === void 0) { useCache = false; }
387
+ if (useCache && cookieParsingCache) {
388
+ return cookieParsingCache;
389
+ }
390
+ var res = parseCookieString(document.cookie);
391
+ cookieParsingCache = res;
392
+ return res;
393
+ };
394
+ // Methods partially borrowed from quirksmode.org/js/cookies.html
395
+ var getCookie = function (name) {
396
+ if (!name) {
397
+ return null;
398
+ }
399
+ try {
400
+ var nameEQ = name + '=';
401
+ var ca = requireWindow().document.cookie.split(';');
402
+ for (var i = 0; i < ca.length; i++) {
403
+ var c = ca[i];
404
+ while (c.charAt(0) == ' ') {
405
+ c = c.substring(1, c.length);
406
+ }
407
+ if (c.indexOf(nameEQ) === 0) {
408
+ return decodeURIComponent(c.substring(nameEQ.length, c.length));
409
+ }
410
+ }
411
+ }
412
+ catch (err) {
413
+ getLogger().error("getCookies", err);
414
+ }
415
+ return null;
416
+ };
417
+ var setCookie = function (name, value, opts) {
418
+ if (opts === void 0) { opts = {}; }
419
+ requireWindow().document.cookie = serializeCookie(name, value, opts);
420
+ };
421
+ var deleteCookie = function (name, path) {
422
+ if (path === void 0) { path = "/"; }
423
+ document.cookie = name + "= ; SameSite=Strict; expires = Thu, 01 Jan 1970 00:00:00 GMT" + (path ? ("; path = " + path) : "");
424
+ };
425
+ var generateId = function () { return Math.random().toString(36).substring(2, 12); };
426
+ var getUmExclusionState = function () {
427
+ var state = "false";
428
+ if (typeof window !== 'undefined' && window.localStorage) {
429
+ state = localStorage.getItem("um_exclusion");
430
+ }
431
+ return state === undefined || state === null || state === "false" ? false : true;
432
+ };
433
+ var generateRandom = function () { return Math.random().toString(36).substring(2, 7); };
434
+ var parseQuery = function (qs) {
435
+ if (!qs) {
436
+ return {};
437
+ }
438
+ var queryString = qs.length > 0 && qs.charAt(0) === "?" ? qs.substring(1) : qs;
439
+ var query = {};
440
+ var pairs = (queryString[0] === "?" ? queryString.substr(1) : queryString).split("&");
441
+ for (var i = 0; i < pairs.length; i++) {
442
+ var pair = pairs[i].split("=");
443
+ query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || "");
444
+ }
445
+ return query;
446
+ };
447
+ var UTM_TYPES = {
448
+ utm_source: "source",
449
+ utm_medium: "medium",
450
+ utm_campaign: "campaign",
451
+ utm_term: "term",
452
+ utm_content: "content"
453
+ };
454
+ var CLICK_IDS = {
455
+ gclid: true,
456
+ fbclid: true,
457
+ dclid: true
458
+ };
459
+ var getDataFromParams = function (params) {
460
+ var result = {
461
+ utm: {},
462
+ click_id: {},
463
+ };
464
+ for (var name in params) {
465
+ if (!params.hasOwnProperty(name)) {
466
+ continue;
467
+ }
468
+ var val = params[name];
469
+ var utm = UTM_TYPES[name];
470
+ if (utm) {
471
+ result.utm[utm] = val;
472
+ }
473
+ else if (CLICK_IDS[name]) {
474
+ result.click_id[name] = val;
475
+ }
476
+ }
477
+ return result;
478
+ };
479
+ //2020-08-24T13:42:16.439Z -> 2020-08-24T13:42:16.439123Z
480
+ var reformatDate = function (strDate) {
481
+ var end = strDate.split(".")[1];
482
+ if (!end) {
483
+ return strDate;
484
+ }
485
+ if (end.length >= 7) {
486
+ return strDate;
487
+ }
488
+ return strDate.slice(0, -1) + "0".repeat(7 - end.length) + "Z";
489
+ };
490
+ function endsWith(str, suffix) {
491
+ return str.indexOf(suffix, str.length - suffix.length) !== -1;
492
+ }
493
+ var getHostWithProtocol = function (host) {
494
+ while (endsWith(host, "/")) {
495
+ host = host.substr(0, host.length - 1);
496
+ }
497
+ if (host.indexOf("https://") === 0 || host.indexOf("http://") === 0) {
498
+ return host;
499
+ }
500
+ else {
501
+ return "https://" + host;
502
+ }
503
+ };
504
+
505
+ var MemoryQueue = /** @class */ (function () {
506
+ function MemoryQueue() {
507
+ this.queue = [];
508
+ }
509
+ MemoryQueue.prototype.flush = function () {
510
+ var queue = this.queue;
511
+ this.queue = [];
512
+ return queue;
513
+ };
514
+ MemoryQueue.prototype.push = function () {
515
+ var _a;
516
+ var values = [];
517
+ for (var _i = 0; _i < arguments.length; _i++) {
518
+ values[_i] = arguments[_i];
519
+ }
520
+ (_a = this.queue).push.apply(_a, values);
521
+ };
522
+ return MemoryQueue;
523
+ }());
524
+ var LocalStorageQueue = /** @class */ (function () {
525
+ function LocalStorageQueue(key) {
526
+ this.key = key;
527
+ }
528
+ LocalStorageQueue.prototype.flush = function () {
529
+ var queue = this.get();
530
+ if (queue.length) {
531
+ this.set([]);
532
+ }
533
+ return queue;
534
+ };
535
+ LocalStorageQueue.prototype.push = function () {
536
+ var values = [];
537
+ for (var _i = 0; _i < arguments.length; _i++) {
538
+ values[_i] = arguments[_i];
539
+ }
540
+ var queue = this.get();
541
+ queue.push.apply(queue, values);
542
+ this.set(queue);
543
+ };
544
+ LocalStorageQueue.prototype.set = function (queue) {
545
+ localStorage.setItem(this.key, JSON.stringify(queue));
546
+ };
547
+ LocalStorageQueue.prototype.get = function () {
548
+ var data = localStorage.getItem(this.key);
549
+ if (data !== null && data !== "") {
550
+ return JSON.parse(data);
551
+ }
552
+ return [];
553
+ };
554
+ return LocalStorageQueue;
555
+ }());
556
+
557
+ var ObjProto = Object.prototype;
558
+ var toString = ObjProto.toString;
559
+ var hasOwnProperty = ObjProto.hasOwnProperty;
560
+ var ArrayProto = Array.prototype;
561
+ var nativeForEach = ArrayProto.forEach, nativeIsArray = Array.isArray, breaker = {};
562
+ var _isArray = nativeIsArray ||
563
+ function (obj) {
564
+ return toString.call(obj) === '[object Array]';
565
+ };
566
+ function _eachArray(obj, iterator, thisArg) {
567
+ if (Array.isArray(obj)) {
568
+ if (nativeForEach && obj.forEach === nativeForEach) {
569
+ obj.forEach(iterator, thisArg);
570
+ }
571
+ else if ('length' in obj && obj.length === +obj.length) {
572
+ for (var i = 0, l = obj.length; i < l; i++) {
573
+ if (i in obj && iterator.call(thisArg, obj[i], i) === breaker) {
574
+ return;
575
+ }
576
+ }
577
+ }
578
+ }
579
+ }
580
+ // Embed part of the Underscore Library
581
+ var _trim = function (str) {
582
+ return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
583
+ };
584
+ var _bind_instance_methods = function (obj) {
585
+ for (var func in obj) {
586
+ if (typeof obj[func] === 'function') {
587
+ obj[func] = obj[func].bind(obj);
588
+ }
589
+ }
590
+ };
591
+ /**
592
+ * @param {*=} obj
593
+ * @param {function(...*)=} iterator
594
+ * @param {Object=} thisArg
595
+ */
596
+ function _each(obj, iterator, thisArg) {
597
+ if (obj === null || obj === undefined) {
598
+ return;
599
+ }
600
+ if (nativeForEach && Array.isArray(obj) && obj.forEach === nativeForEach) {
601
+ obj.forEach(iterator, thisArg);
602
+ }
603
+ else if ('length' in obj && obj.length === +obj.length) {
604
+ for (var i = 0, l = obj.length; i < l; i++) {
605
+ if (i in obj && iterator.call(thisArg, obj[i], i) === breaker) {
606
+ return;
607
+ }
608
+ }
609
+ }
610
+ else {
611
+ for (var key in obj) {
612
+ if (hasOwnProperty.call(obj, key)) {
613
+ if (iterator.call(thisArg, obj[key], key) === breaker) {
614
+ return;
615
+ }
616
+ }
617
+ }
618
+ }
619
+ }
620
+ var _extend = function (obj) {
621
+ var args = [];
622
+ for (var _i = 1; _i < arguments.length; _i++) {
623
+ args[_i - 1] = arguments[_i];
624
+ }
625
+ _eachArray(args, function (source) {
626
+ for (var prop in source) {
627
+ if (source[prop] !== void 0) {
628
+ obj[prop] = source[prop];
629
+ }
630
+ }
631
+ });
632
+ return obj;
633
+ };
634
+ function _includes(str, needle) {
635
+ return str.indexOf(needle) !== -1;
636
+ }
637
+ // from a comment on http://dbj.org/dbj/?p=286
638
+ // fails on only one very rare and deliberate custom object:
639
+ // let bomb = { toString : undefined, valueOf: function(o) { return "function BOMBA!"; }};
640
+ var _isFunction = function (f) {
641
+ try {
642
+ return /^\s*\bfunction\b/.test(f);
643
+ }
644
+ catch (x) {
645
+ return false;
646
+ }
647
+ };
648
+ var _isUndefined = function (obj) {
649
+ return obj === void 0;
650
+ };
651
+ var _register_event = (function () {
652
+ // written by Dean Edwards, 2005
653
+ // with input from Tino Zijdel - crisp@xs4all.nl
654
+ // with input from Carl Sverre - mail@carlsverre.com
655
+ // with input from PostHog
656
+ // http://dean.edwards.name/weblog/2005/10/add-event/
657
+ // https://gist.github.com/1930440
658
+ /**
659
+ * @param {Object} element
660
+ * @param {string} type
661
+ * @param {function(...*)} handler
662
+ * @param {boolean=} oldSchool
663
+ * @param {boolean=} useCapture
664
+ */
665
+ var register_event = function (element, type, handler, oldSchool, useCapture) {
666
+ if (!element) {
667
+ getLogger().error('No valid element provided to register_event');
668
+ return;
669
+ }
670
+ if (element.addEventListener && !oldSchool) {
671
+ element.addEventListener(type, handler, !!useCapture);
672
+ }
673
+ else {
674
+ var ontype = 'on' + type;
675
+ var old_handler = element[ontype] // can be undefined
676
+ ;
677
+ element[ontype] = makeHandler(element, handler, old_handler);
678
+ }
679
+ };
680
+ function makeHandler(element, new_handler, old_handlers) {
681
+ return function (event) {
682
+ event = event || fixEvent(window.event);
683
+ // this basically happens in firefox whenever another script
684
+ // overwrites the onload callback and doesn't pass the event
685
+ // object to previously defined callbacks. All the browsers
686
+ // that don't define window.event implement addEventListener
687
+ // so the dom_loaded handler will still be fired as usual.
688
+ if (!event) {
689
+ return undefined;
690
+ }
691
+ var ret = true;
692
+ var old_result;
693
+ if (_isFunction(old_handlers)) {
694
+ old_result = old_handlers(event);
695
+ }
696
+ var new_result = new_handler.call(element, event);
697
+ if (false === old_result || false === new_result) {
698
+ ret = false;
699
+ }
700
+ return ret;
701
+ };
702
+ }
703
+ function fixEvent(event) {
704
+ if (event) {
705
+ event.preventDefault = fixEvent.preventDefault;
706
+ event.stopPropagation = fixEvent.stopPropagation;
707
+ }
708
+ return event;
709
+ }
710
+ fixEvent.preventDefault = function () {
711
+ this.returnValue = false;
712
+ };
713
+ fixEvent.stopPropagation = function () {
714
+ this.cancelBubble = true;
715
+ };
716
+ return register_event;
717
+ })();
718
+ var _safewrap = function (f) {
719
+ return function () {
720
+ var args = [];
721
+ for (var _i = 0; _i < arguments.length; _i++) {
722
+ args[_i] = arguments[_i];
723
+ }
724
+ try {
725
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
726
+ // @ts-ignore
727
+ return f.apply(this, args);
728
+ }
729
+ catch (e) {
730
+ getLogger().error('Implementation error. Please turn on debug and contact support@usermaven.com.', e);
731
+ // if (Config.DEBUG) {
732
+ // getLogger.critical(e)
733
+ // }
734
+ }
735
+ };
736
+ };
737
+ var _safewrap_instance_methods = function (obj) {
738
+ for (var func in obj) {
739
+ if (typeof obj[func] === 'function') {
740
+ obj[func] = _safewrap(obj[func]);
741
+ }
742
+ }
743
+ };
744
+ var COPY_IN_PROGRESS_ATTRIBUTE = typeof Symbol !== 'undefined' ? Symbol('__deepCircularCopyInProgress__') : '__deepCircularCopyInProgress__';
745
+ /**
746
+ * Deep copies an object.
747
+ * It handles cycles by replacing all references to them with `undefined`
748
+ * Also supports customizing native values
749
+ *
750
+ * @param value
751
+ * @param customizer
752
+ * @param [key] if provided this is the object key associated with the value to be copied. It allows the customizer function to have context when it runs
753
+ * @returns {{}|undefined|*}
754
+ */
755
+ function deepCircularCopy(value, customizer, key) {
756
+ if (value !== Object(value))
757
+ return customizer ? customizer(value, key) : value; // primitive value
758
+ if (value[COPY_IN_PROGRESS_ATTRIBUTE])
759
+ return undefined;
760
+ value[COPY_IN_PROGRESS_ATTRIBUTE] = true;
761
+ var result;
762
+ if (_isArray(value)) {
763
+ result = [];
764
+ _eachArray(value, function (it) {
765
+ result.push(deepCircularCopy(it, customizer));
766
+ });
767
+ }
768
+ else {
769
+ result = {};
770
+ _each(value, function (val, key) {
771
+ if (key !== COPY_IN_PROGRESS_ATTRIBUTE) {
772
+ result[key] = deepCircularCopy(val, customizer, key);
773
+ }
774
+ });
775
+ }
776
+ delete value[COPY_IN_PROGRESS_ATTRIBUTE];
777
+ return result;
778
+ }
779
+ var LONG_STRINGS_ALLOW_LIST = ['$performance_raw'];
780
+ function _copyAndTruncateStrings(object, maxStringLength) {
781
+ return deepCircularCopy(object, function (value, key) {
782
+ if (key && LONG_STRINGS_ALLOW_LIST.indexOf(key) > -1) {
783
+ return value;
784
+ }
785
+ if (typeof value === 'string' && maxStringLength !== null) {
786
+ return value.slice(0, maxStringLength);
787
+ }
788
+ return value;
789
+ });
790
+ }
791
+
792
+ /*
793
+ * Get the className of an element, accounting for edge cases where element.className is an object
794
+ * @param {Element} el - element to get the className of
795
+ * @returns {string} the element's class
796
+ */
797
+ function getClassName(el) {
798
+ switch (typeof el.className) {
799
+ case 'string':
800
+ return el.className;
801
+ // TODO: when is this ever used?
802
+ case 'object': // handle cases where className might be SVGAnimatedString or some other type
803
+ return ('baseVal' in el.className ? el.className.baseVal : null) || el.getAttribute('class') || '';
804
+ default:
805
+ // future proof
806
+ return '';
807
+ }
808
+ }
809
+ /*
810
+ * Get the direct text content of an element, protecting against sensitive data collection.
811
+ * Concats textContent of each of the element's text node children; this avoids potential
812
+ * collection of sensitive data that could happen if we used element.textContent and the
813
+ * element had sensitive child elements, since element.textContent includes child content.
814
+ * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).
815
+ * @param {Element} el - element to get the text of
816
+ * @returns {string} the element's direct text content
817
+ */
818
+ function getSafeText(el) {
819
+ var elText = '';
820
+ if (shouldCaptureElement(el) && !isSensitiveElement(el) && el.childNodes && el.childNodes.length) {
821
+ _each(el.childNodes, function (child) {
822
+ if (isTextNode(child) && child.textContent) {
823
+ elText += _trim(child.textContent)
824
+ // scrub potentially sensitive values
825
+ .split(/(\s+)/)
826
+ .filter(shouldCaptureValue)
827
+ .join('')
828
+ // normalize whitespace
829
+ .replace(/[\r\n]/g, ' ')
830
+ .replace(/[ ]+/g, ' ')
831
+ // truncate
832
+ .substring(0, 255);
833
+ }
834
+ });
835
+ }
836
+ return _trim(elText);
837
+ }
838
+ /*
839
+ * Check whether an element has nodeType Node.ELEMENT_NODE
840
+ * @param {Element} el - element to check
841
+ * @returns {boolean} whether el is of the correct nodeType
842
+ */
843
+ function isElementNode(el) {
844
+ return !!el && el.nodeType === 1; // Node.ELEMENT_NODE - use integer constant for browser portability
845
+ }
846
+ /*
847
+ * Check whether an element is of a given tag type.
848
+ * Due to potential reference discrepancies (such as the webcomponents.js polyfill),
849
+ * we want to match tagNames instead of specific references because something like
850
+ * element === document.body won't always work because element might not be a native
851
+ * element.
852
+ * @param {Element} el - element to check
853
+ * @param {string} tag - tag name (e.g., "div")
854
+ * @returns {boolean} whether el is of the given tag type
855
+ */
856
+ function isTag(el, tag) {
857
+ return !!el && !!el.tagName && el.tagName.toLowerCase() === tag.toLowerCase();
858
+ }
859
+ /*
860
+ * Check whether an element has nodeType Node.TEXT_NODE
861
+ * @param {Element} el - element to check
862
+ * @returns {boolean} whether el is of the correct nodeType
863
+ */
864
+ function isTextNode(el) {
865
+ return !!el && el.nodeType === 3; // Node.TEXT_NODE - use integer constant for browser portability
866
+ }
867
+ /*
868
+ * Check whether an element has nodeType Node.DOCUMENT_FRAGMENT_NODE
869
+ * @param {Element} el - element to check
870
+ * @returns {boolean} whether el is of the correct nodeType
871
+ */
872
+ function isDocumentFragment(el) {
873
+ return !!el && el.nodeType === 11; // Node.DOCUMENT_FRAGMENT_NODE - use integer constant for browser portability
874
+ }
875
+ var usefulElements = ['a', 'button', 'form', 'input', 'select', 'textarea', 'label'];
876
+ /*
877
+ * Check whether a DOM event should be "captured" or if it may contain sentitive data
878
+ * using a variety of heuristics.
879
+ * @param {Element} el - element to check
880
+ * @param {Event} event - event to check
881
+ * @returns {boolean} whether the event should be captured
882
+ */
883
+ function shouldCaptureDomEvent(el, event) {
884
+ if (!el || isTag(el, 'html') || !isElementNode(el)) {
885
+ return false;
886
+ }
887
+ // allow users to programmatically prevent capturing of elements by adding class 'um-no-capture'
888
+ if (el.classList && el.classList.contains('um-no-capture')) {
889
+ return false;
890
+ }
891
+ var parentIsUsefulElement = false;
892
+ var targetElementList = [el]; // TODO: remove this var, it's never queried
893
+ var parentNode = true;
894
+ var curEl = el;
895
+ while (curEl.parentNode && !isTag(curEl, 'body')) {
896
+ // If element is a shadow root, we skip it
897
+ if (isDocumentFragment(curEl.parentNode)) {
898
+ targetElementList.push(curEl.parentNode.host);
899
+ curEl = curEl.parentNode.host;
900
+ continue;
901
+ }
902
+ parentNode = curEl.parentNode || false;
903
+ if (!parentNode)
904
+ break;
905
+ if (usefulElements.indexOf(parentNode.tagName.toLowerCase()) > -1) {
906
+ parentIsUsefulElement = true;
907
+ }
908
+ else {
909
+ var compStyles_1 = window.getComputedStyle(parentNode);
910
+ if (compStyles_1 && compStyles_1.getPropertyValue('cursor') === 'pointer') {
911
+ parentIsUsefulElement = true;
912
+ }
913
+ }
914
+ targetElementList.push(parentNode);
915
+ curEl = parentNode;
916
+ }
917
+ var compStyles = window.getComputedStyle(el);
918
+ if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer' && event.type === 'click') {
919
+ return true;
920
+ }
921
+ var tag = el.tagName.toLowerCase();
922
+ switch (tag) {
923
+ case 'html':
924
+ return false;
925
+ case 'form':
926
+ return event.type === 'submit';
927
+ case 'input':
928
+ return event.type === 'change' || event.type === 'click';
929
+ case 'select':
930
+ case 'textarea':
931
+ return event.type === 'change' || event.type === 'click';
932
+ default:
933
+ if (parentIsUsefulElement)
934
+ return event.type === 'click';
935
+ return (event.type === 'click' &&
936
+ (usefulElements.indexOf(tag) > -1 || el.getAttribute('contenteditable') === 'true'));
937
+ }
938
+ }
939
+ /*
940
+ * Check whether a DOM element should be "captured" or if it may contain sentitive data
941
+ * using a variety of heuristics.
942
+ * @param {Element} el - element to check
943
+ * @returns {boolean} whether the element should be captured
944
+ */
945
+ function shouldCaptureElement(el) {
946
+ for (var curEl = el; curEl.parentNode && !isTag(curEl, 'body'); curEl = curEl.parentNode) {
947
+ var classes = getClassName(curEl).split(' ');
948
+ if (_includes(classes, 'ph-sensitive') || _includes(classes, 'ph-no-capture')) {
949
+ return false;
950
+ }
951
+ }
952
+ if (_includes(getClassName(el).split(' '), 'ph-include')) {
953
+ return true;
954
+ }
955
+ // don't include hidden or password fields
956
+ var type = el.type || '';
957
+ if (typeof type === 'string') {
958
+ // it's possible for el.type to be a DOM element if el is a form with a child input[name="type"]
959
+ switch (type.toLowerCase()) {
960
+ case 'hidden':
961
+ return false;
962
+ case 'password':
963
+ return false;
964
+ }
965
+ }
966
+ // filter out data from fields that look like sensitive fields
967
+ var name = el.name || el.id || '';
968
+ // See https://github.com/posthog/posthog-js/issues/165
969
+ // Under specific circumstances a bug caused .replace to be called on a DOM element
970
+ // instead of a string, removing the element from the page. Ensure this issue is mitigated.
971
+ if (typeof name === 'string') {
972
+ // it's possible for el.name or el.id to be a DOM element if el is a form with a child input[name="name"]
973
+ var sensitiveNameRegex = /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i;
974
+ if (sensitiveNameRegex.test(name.replace(/[^a-zA-Z0-9]/g, ''))) {
975
+ return false;
976
+ }
977
+ }
978
+ return true;
979
+ }
980
+ /*
981
+ * Check whether a DOM element is 'sensitive' and we should only capture limited data
982
+ * @param {Element} el - element to check
983
+ * @returns {boolean} whether the element should be captured
984
+ */
985
+ function isSensitiveElement(el) {
986
+ // don't send data from inputs or similar elements since there will always be
987
+ // a risk of clientside javascript placing sensitive data in attributes
988
+ var allowedInputTypes = ['button', 'checkbox', 'submit', 'reset'];
989
+ if ((isTag(el, 'input') && !allowedInputTypes.includes(el.type)) ||
990
+ isTag(el, 'select') ||
991
+ isTag(el, 'textarea') ||
992
+ el.getAttribute('contenteditable') === 'true') {
993
+ return true;
994
+ }
995
+ return false;
996
+ }
997
+ /*
998
+ * Check whether a string value should be "captured" or if it may contain sentitive data
999
+ * using a variety of heuristics.
1000
+ * @param {string} value - string value to check
1001
+ * @returns {boolean} whether the element should be captured
1002
+ */
1003
+ function shouldCaptureValue(value) {
1004
+ if (value === null || _isUndefined(value)) {
1005
+ return false;
1006
+ }
1007
+ if (typeof value === 'string') {
1008
+ value = _trim(value);
1009
+ // check to see if input value looks like a credit card number
1010
+ // see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html
1011
+ var ccRegex = /^(?:(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}))$/;
1012
+ if (ccRegex.test((value || '').replace(/[- ]/g, ''))) {
1013
+ return false;
1014
+ }
1015
+ // check to see if input value looks like a social security number
1016
+ var ssnRegex = /(^\d{3}-?\d{2}-?\d{4}$)/;
1017
+ if (ssnRegex.test(value)) {
1018
+ return false;
1019
+ }
1020
+ }
1021
+ return true;
1022
+ }
1023
+ /*
1024
+ * Check whether an attribute name is an Angular style attr (either _ngcontent or _nghost)
1025
+ * These update on each build and lead to noise in the element chain
1026
+ * More details on the attributes here: https://angular.io/guide/view-encapsulation
1027
+ * @param {string} attributeName - string value to check
1028
+ * @returns {boolean} whether the element is an angular tag
1029
+ */
1030
+ function isAngularStyleAttr(attributeName) {
1031
+ if (typeof attributeName === 'string') {
1032
+ return attributeName.substring(0, 10) === '_ngcontent' || attributeName.substring(0, 7) === '_nghost';
1033
+ }
1034
+ return false;
1035
+ }
1036
+
1037
+ // Naive rage click implementation: If mouse has not moved than RAGE_CLICK_THRESHOLD_PX
1038
+ // over RAGE_CLICK_CLICK_COUNT clicks with max RAGE_CLICK_TIMEOUT_MS between clicks, it's
1039
+ // counted as a rage click
1040
+ var RAGE_CLICK_THRESHOLD_PX = 30;
1041
+ var RAGE_CLICK_TIMEOUT_MS = 1000;
1042
+ var RAGE_CLICK_CLICK_COUNT = 3;
1043
+ var RageClick = /** @class */ (function () {
1044
+ function RageClick(instance, enabled) {
1045
+ if (enabled === void 0) { enabled = false; }
1046
+ this.clicks = [];
1047
+ this.instance = instance;
1048
+ this.enabled = enabled;
1049
+ }
1050
+ RageClick.prototype.click = function (x, y, timestamp) {
1051
+ if (!this.enabled) {
1052
+ return;
1053
+ }
1054
+ var lastClick = this.clicks[this.clicks.length - 1];
1055
+ if (lastClick &&
1056
+ Math.abs(x - lastClick.x) + Math.abs(y - lastClick.y) < RAGE_CLICK_THRESHOLD_PX &&
1057
+ timestamp - lastClick.timestamp < RAGE_CLICK_TIMEOUT_MS) {
1058
+ this.clicks.push({ x: x, y: y, timestamp: timestamp });
1059
+ if (this.clicks.length === RAGE_CLICK_CLICK_COUNT) {
1060
+ this.instance.capture('$rageclick');
1061
+ }
1062
+ }
1063
+ else {
1064
+ this.clicks = [{ x: x, y: y, timestamp: timestamp }];
1065
+ }
1066
+ };
1067
+ return RageClick;
1068
+ }());
1069
+
1070
+ /**
1071
+ * Scroll extension to add scroll get scroll depth in percentage
1072
+ */
1073
+ var ScrollDepth = /** @class */ (function () {
1074
+ function ScrollDepth(instance) {
1075
+ this.instance = instance;
1076
+ this.lastScrollDepth = 0;
1077
+ this.canSend = true;
1078
+ this.documentElement = document.documentElement;
1079
+ }
1080
+ /**
1081
+ * Track scroll depth
1082
+ * @description this function will be called on every scroll event to track scroll depth
1083
+ */
1084
+ ScrollDepth.prototype.track = function () {
1085
+ var scrollDepth = this.getScrollDepth();
1086
+ // If scroll depth is greater than last scroll depth, then update last scroll depth
1087
+ // We are doing this to only get the maximum scroll depth
1088
+ if (scrollDepth > this.lastScrollDepth) {
1089
+ this.lastScrollDepth = scrollDepth;
1090
+ this.canSend = true;
1091
+ }
1092
+ };
1093
+ /**
1094
+ * Send scroll depth event
1095
+ * @description this function will be when we want to send scroll depth event e.g. on page visibility change
1096
+ */
1097
+ ScrollDepth.prototype.send = function (eventType) {
1098
+ if (eventType === void 0) { eventType = "$scroll"; }
1099
+ if (!this.canSend) {
1100
+ return;
1101
+ }
1102
+ // Creating payload
1103
+ var props = {
1104
+ percent: this.lastScrollDepth,
1105
+ window_height: this.getWindowHeight(),
1106
+ document_height: this.getDocumentHeight(),
1107
+ scroll_distance: this.getScrollDistance()
1108
+ };
1109
+ // Sending event
1110
+ this.instance.capture(eventType, props);
1111
+ // Setting canSend to false, for avoiding sending multiple events
1112
+ this.canSend = false;
1113
+ };
1114
+ /**
1115
+ * Core method to get scroll depth
1116
+ */
1117
+ ScrollDepth.prototype.getScrollDepth = function () {
1118
+ try {
1119
+ // Get the height of the window and the document body
1120
+ var winHeight = this.getWindowHeight();
1121
+ var docHeight = this.getDocumentHeight();
1122
+ // Get the current scroll position and the length of the track
1123
+ var scrollTop = this.getScrollDistance();
1124
+ var trackLength = docHeight - winHeight;
1125
+ // Calculate the scroll depth as a percentage
1126
+ return Math.min(100, Math.floor(scrollTop / trackLength * 100));
1127
+ }
1128
+ catch (e) {
1129
+ return 0;
1130
+ }
1131
+ };
1132
+ /**
1133
+ * Core method to get window height
1134
+ */
1135
+ ScrollDepth.prototype.getWindowHeight = function () {
1136
+ try {
1137
+ return window.innerHeight || this.documentElement.clientHeight ||
1138
+ document.body.clientHeight || 0;
1139
+ }
1140
+ catch (e) {
1141
+ return 0;
1142
+ }
1143
+ };
1144
+ /**
1145
+ * Core method to get document height
1146
+ */
1147
+ ScrollDepth.prototype.getDocumentHeight = function () {
1148
+ try {
1149
+ return Math.max(document.body.scrollHeight || 0, this.documentElement.scrollHeight || 0, document.body.offsetHeight || 0, this.documentElement.offsetHeight || 0, document.body.clientHeight || 0, this.documentElement.clientHeight || 0);
1150
+ }
1151
+ catch (e) {
1152
+ return 0;
1153
+ }
1154
+ };
1155
+ /**
1156
+ * Core method to get scroll distance
1157
+ */
1158
+ ScrollDepth.prototype.getScrollDistance = function () {
1159
+ try {
1160
+ return window.scrollY || window.pageYOffset || document.body.scrollTop ||
1161
+ this.documentElement.scrollTop || 0;
1162
+ }
1163
+ catch (e) {
1164
+ return 0;
1165
+ }
1166
+ };
1167
+ return ScrollDepth;
1168
+ }());
1169
+
1170
+ var autocapture = {
1171
+ _initializedTokens: [],
1172
+ _previousElementSibling: function (el) {
1173
+ if (el.previousElementSibling) {
1174
+ return el.previousElementSibling;
1175
+ }
1176
+ else {
1177
+ var _el = el;
1178
+ do {
1179
+ _el = _el.previousSibling; // resolves to ChildNode->Node, which is Element's parent class
1180
+ } while (_el && !isElementNode(_el));
1181
+ return _el;
1182
+ }
1183
+ },
1184
+ _getPropertiesFromElement: function (elem, maskInputs, maskText) {
1185
+ var tag_name = elem.tagName.toLowerCase();
1186
+ var props = {
1187
+ tag_name: tag_name,
1188
+ };
1189
+ if (usefulElements.indexOf(tag_name) > -1 && !maskText) {
1190
+ props['$el_text'] = getSafeText(elem);
1191
+ }
1192
+ var classes = getClassName(elem);
1193
+ if (classes.length > 0)
1194
+ props['classes'] = classes.split(' ').filter(function (c) {
1195
+ return c !== '';
1196
+ });
1197
+ _each(elem.attributes, function (attr) {
1198
+ // Only capture attributes we know are safe
1199
+ if (isSensitiveElement(elem) && ['name', 'id', 'class'].indexOf(attr.name) === -1)
1200
+ return;
1201
+ if (!maskInputs && shouldCaptureValue(attr.value) && !isAngularStyleAttr(attr.name)) {
1202
+ props['attr__' + attr.name] = attr.value;
1203
+ }
1204
+ });
1205
+ var nthChild = 1;
1206
+ var nthOfType = 1;
1207
+ var currentElem = elem;
1208
+ while ((currentElem = this._previousElementSibling(currentElem))) {
1209
+ // eslint-disable-line no-cond-assign
1210
+ nthChild++;
1211
+ if (currentElem.tagName === elem.tagName) {
1212
+ nthOfType++;
1213
+ }
1214
+ }
1215
+ props['nth_child'] = nthChild;
1216
+ props['nth_of_type'] = nthOfType;
1217
+ return props;
1218
+ },
1219
+ _getDefaultProperties: function (eventType) {
1220
+ return {
1221
+ $event_type: eventType,
1222
+ $ce_version: 1,
1223
+ };
1224
+ },
1225
+ _extractCustomPropertyValue: function (customProperty) {
1226
+ var propValues = [];
1227
+ _each(document.querySelectorAll(customProperty['css_selector']), function (matchedElem) {
1228
+ var value;
1229
+ if (['input', 'select'].indexOf(matchedElem.tagName.toLowerCase()) > -1) {
1230
+ value = matchedElem['value'];
1231
+ }
1232
+ else if (matchedElem['textContent']) {
1233
+ value = matchedElem['textContent'];
1234
+ }
1235
+ if (shouldCaptureValue(value)) {
1236
+ propValues.push(value);
1237
+ }
1238
+ });
1239
+ return propValues.join(', ');
1240
+ },
1241
+ // TODO: delete custom_properties after changeless typescript refactor
1242
+ _getCustomProperties: function (targetElementList) {
1243
+ var _this = this;
1244
+ var props = {}; // will be deleted
1245
+ _each(this._customProperties, function (customProperty) {
1246
+ _each(customProperty['event_selectors'], function (eventSelector) {
1247
+ var eventElements = document.querySelectorAll(eventSelector);
1248
+ _each(eventElements, function (eventElement) {
1249
+ if (_includes(targetElementList, eventElement) && shouldCaptureElement(eventElement)) {
1250
+ props[customProperty['name']] = _this._extractCustomPropertyValue(customProperty);
1251
+ }
1252
+ });
1253
+ });
1254
+ });
1255
+ return props;
1256
+ },
1257
+ _getEventTarget: function (e) {
1258
+ var _a;
1259
+ // https://developer.mozilla.org/en-US/docs/Web/API/Event/target#Compatibility_notes
1260
+ if (typeof e.target === 'undefined') {
1261
+ return e.srcElement || null;
1262
+ }
1263
+ else {
1264
+ if ((_a = e.target) === null || _a === void 0 ? void 0 : _a.shadowRoot) {
1265
+ return e.composedPath()[0] || null;
1266
+ }
1267
+ return e.target || null;
1268
+ }
1269
+ },
1270
+ _captureEvent: function (e, instance, opts) {
1271
+ var _this = this;
1272
+ var _a;
1273
+ /*** Don't mess with this code without running IE8 tests on it ***/
1274
+ var target = this._getEventTarget(e);
1275
+ if (isTextNode(target)) {
1276
+ // defeat Safari bug (see: http://www.quirksmode.org/js/events_properties.html)
1277
+ target = (target.parentNode || null);
1278
+ }
1279
+ // If type is 'scroll', track the scroll depth
1280
+ if (e.type === 'scroll') {
1281
+ this.scrollDepth.track();
1282
+ return true;
1283
+ }
1284
+ // If type is visibilitychange and the page is about to be hidden, send a scroll depth event
1285
+ if ((e.type === 'visibilitychange' && document.visibilityState === 'hidden') || e.type === 'popstate') {
1286
+ this.scrollDepth.send();
1287
+ return true;
1288
+ }
1289
+ if (e.type === 'click' && e instanceof MouseEvent) {
1290
+ (_a = this.rageclicks) === null || _a === void 0 ? void 0 : _a.click(e.clientX, e.clientY, new Date().getTime());
1291
+ }
1292
+ if (target && shouldCaptureDomEvent(target, e)) {
1293
+ var targetElementList = [target];
1294
+ var curEl = target;
1295
+ while (curEl.parentNode && !isTag(curEl, 'body')) {
1296
+ if (isDocumentFragment(curEl.parentNode)) {
1297
+ targetElementList.push(curEl.parentNode.host);
1298
+ curEl = curEl.parentNode.host;
1299
+ continue;
1300
+ }
1301
+ targetElementList.push(curEl.parentNode);
1302
+ curEl = curEl.parentNode;
1303
+ }
1304
+ var elementsJson_1 = [];
1305
+ var href_1, explicitNoCapture_1 = false;
1306
+ _each(targetElementList, function (el) {
1307
+ var shouldCaptureEl = shouldCaptureElement(el);
1308
+ // if the element or a parent element is an anchor tag
1309
+ // include the href as a property
1310
+ if (el.tagName.toLowerCase() === 'a') {
1311
+ href_1 = el.getAttribute('href');
1312
+ href_1 = shouldCaptureEl && shouldCaptureValue(href_1) && href_1;
1313
+ }
1314
+ // allow users to programmatically prevent capturing of elements by adding class 'ph-no-capture'
1315
+ var classes = getClassName(el).split(' ');
1316
+ if (_includes(classes, 'ph-no-capture')) {
1317
+ explicitNoCapture_1 = true;
1318
+ }
1319
+ elementsJson_1.push(_this._getPropertiesFromElement(el, opts === null || opts === void 0 ? void 0 : opts.mask_all_element_attributes, opts === null || opts === void 0 ? void 0 : opts.mask_all_text));
1320
+ });
1321
+ if (!(opts === null || opts === void 0 ? void 0 : opts.mask_all_text)) {
1322
+ elementsJson_1[0]['$el_text'] = getSafeText(target);
1323
+ }
1324
+ if (href_1) {
1325
+ elementsJson_1[0]['attr__href'] = href_1;
1326
+ }
1327
+ if (explicitNoCapture_1) {
1328
+ return false;
1329
+ }
1330
+ var props = _extend(this._getDefaultProperties(e.type), {
1331
+ $elements: elementsJson_1,
1332
+ }, this._getCustomProperties(targetElementList));
1333
+ instance.capture('$autocapture', props);
1334
+ return true;
1335
+ }
1336
+ },
1337
+ // only reason is to stub for unit tests
1338
+ // since you can't override window.location props
1339
+ _navigate: function (href) {
1340
+ window.location.href = href;
1341
+ },
1342
+ _addDomEventHandlers: function (instance, opts) {
1343
+ var _this = this;
1344
+ var handler = function (e) {
1345
+ e = e || window.event;
1346
+ _this._captureEvent(e, instance, opts);
1347
+ };
1348
+ _register_event(document, 'submit', handler, false, true);
1349
+ _register_event(document, 'change', handler, false, true);
1350
+ _register_event(document, 'click', handler, false, true);
1351
+ _register_event(document, 'visibilitychange', handler, false, true);
1352
+ _register_event(document, 'scroll', handler, false, true);
1353
+ _register_event(window, 'popstate', handler, false, true);
1354
+ },
1355
+ _customProperties: [],
1356
+ rageclicks: null,
1357
+ scrollDepth: null,
1358
+ opts: {},
1359
+ init: function (instance, opts) {
1360
+ var _this = this;
1361
+ this.rageclicks = new RageClick(instance);
1362
+ this.scrollDepth = new ScrollDepth(instance);
1363
+ this.opts = opts;
1364
+ if (!(document && document.body)) {
1365
+ console.debug('document not ready yet, trying again in 500 milliseconds...');
1366
+ setTimeout(function () {
1367
+ _this.readyAutocapture(instance, opts);
1368
+ }, 500);
1369
+ return;
1370
+ }
1371
+ this.readyAutocapture(instance, opts);
1372
+ },
1373
+ readyAutocapture: function (instance, opts) {
1374
+ this._addDomEventHandlers(instance, opts);
1375
+ },
1376
+ // this is a mechanism to ramp up CE with no server-side interaction.
1377
+ // when CE is active, every page load results in a decide request. we
1378
+ // need to gently ramp this up so we don't overload decide. this decides
1379
+ // deterministically if CE is enabled for this project by modding the char
1380
+ // value of the project token.
1381
+ enabledForProject: function (token, numBuckets, numEnabledBuckets) {
1382
+ if (!token) {
1383
+ return true;
1384
+ }
1385
+ numBuckets = !_isUndefined(numBuckets) ? numBuckets : 10;
1386
+ numEnabledBuckets = !_isUndefined(numEnabledBuckets) ? numEnabledBuckets : 10;
1387
+ var charCodeSum = 0;
1388
+ for (var i = 0; i < token.length; i++) {
1389
+ charCodeSum += token.charCodeAt(i);
1390
+ }
1391
+ return charCodeSum % numBuckets < numEnabledBuckets;
1392
+ },
1393
+ isBrowserSupported: function () {
1394
+ return _isFunction(document.querySelectorAll);
1395
+ },
1396
+ };
1397
+ _bind_instance_methods(autocapture);
1398
+ _safewrap_instance_methods(autocapture);
1399
+
1400
+ var VERSION_INFO = {
1401
+ env: 'production',
1402
+ date: '2023-11-01T06:34:21.101Z',
1403
+ version: '1.2.5'
1404
+ };
1405
+ var USERMAVEN_VERSION = "".concat(VERSION_INFO.version, "/").concat(VERSION_INFO.env, "@").concat(VERSION_INFO.date);
1406
+ var MAX_AGE_TEN_YEARS = 31622400 * 10;
1407
+ var beaconTransport = function (url, json) {
1408
+ getLogger().debug("Sending beacon", json);
1409
+ var blob = new Blob([json], { type: "text/plain" });
1410
+ navigator.sendBeacon(url, blob);
1411
+ return Promise.resolve();
1412
+ };
1413
+ function tryFormat(string) {
1414
+ if (typeof string === "string") {
1415
+ try {
1416
+ return JSON.stringify(JSON.parse(string), null, 2);
1417
+ }
1418
+ catch (e) {
1419
+ return string;
1420
+ }
1421
+ }
1422
+ }
1423
+ var echoTransport = function (url, json) {
1424
+ console.debug("Jitsu client tried to send payload to ".concat(url), tryFormat(json));
1425
+ return Promise.resolve();
1426
+ };
1427
+ // This is a hack to expire all cookies with non-root path left behind by invalid tracking.
1428
+ // TODO remove soon
1429
+ function expireNonRootCookies(name, path) {
1430
+ if (path === void 0) { path = undefined; }
1431
+ path = path !== null && path !== void 0 ? path : window.location.pathname;
1432
+ if (path == "" || path == "/") {
1433
+ return;
1434
+ }
1435
+ deleteCookie(name, path);
1436
+ expireNonRootCookies(name, path.slice(0, path.lastIndexOf("/")));
1437
+ }
1438
+ var CookiePersistence = /** @class */ (function () {
1439
+ function CookiePersistence(cookieDomain, cookieName) {
1440
+ this.cookieDomain = cookieDomain;
1441
+ this.cookieName = cookieName;
1442
+ }
1443
+ CookiePersistence.prototype.save = function (props) {
1444
+ setCookie(this.cookieName, JSON.stringify(props), {
1445
+ domain: this.cookieDomain,
1446
+ secure: document.location.protocol !== "http:",
1447
+ maxAge: MAX_AGE_TEN_YEARS,
1448
+ });
1449
+ };
1450
+ CookiePersistence.prototype.restore = function () {
1451
+ expireNonRootCookies(this.cookieName);
1452
+ var str = getCookie(this.cookieName);
1453
+ if (str) {
1454
+ try {
1455
+ var parsed = JSON.parse(decodeURIComponent(str));
1456
+ if (typeof parsed !== "object") {
1457
+ getLogger().warn("Can't restore value of ".concat(this.cookieName, "@").concat(this.cookieDomain, ", expected to be object, but found ").concat(typeof parsed !== "object", ": ").concat(parsed, ". Ignoring"));
1458
+ return undefined;
1459
+ }
1460
+ return parsed;
1461
+ }
1462
+ catch (e) {
1463
+ getLogger().error("Failed to decode JSON from " + str, e);
1464
+ return undefined;
1465
+ }
1466
+ }
1467
+ return undefined;
1468
+ };
1469
+ CookiePersistence.prototype.delete = function () {
1470
+ deleteCookie(this.cookieName);
1471
+ };
1472
+ return CookiePersistence;
1473
+ }());
1474
+ var NoPersistence = /** @class */ (function () {
1475
+ function NoPersistence() {
1476
+ }
1477
+ NoPersistence.prototype.save = function (props) {
1478
+ };
1479
+ NoPersistence.prototype.restore = function () {
1480
+ return undefined;
1481
+ };
1482
+ NoPersistence.prototype.delete = function () {
1483
+ };
1484
+ return NoPersistence;
1485
+ }());
1486
+ var defaultCompatMode = false;
1487
+ function usermavenClient(opts) {
1488
+ var client = new UsermavenClientImpl();
1489
+ client.init(opts);
1490
+ return client;
1491
+ }
1492
+ var browserEnv = {
1493
+ getSourceIp: function () { return undefined; },
1494
+ describeClient: function () { return ({
1495
+ referer: document.referrer,
1496
+ url: window.location.href,
1497
+ page_title: document.title,
1498
+ doc_path: document.location.pathname,
1499
+ doc_host: document.location.hostname,
1500
+ doc_search: window.location.search,
1501
+ screen_resolution: screen.width + "x" + screen.height,
1502
+ vp_size: Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) +
1503
+ "x" +
1504
+ Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0),
1505
+ user_agent: navigator.userAgent,
1506
+ user_language: navigator.language,
1507
+ doc_encoding: document.characterSet,
1508
+ }); },
1509
+ getAnonymousId: function (_a) {
1510
+ var name = _a.name, domain = _a.domain;
1511
+ expireNonRootCookies(name);
1512
+ var idCookie = getCookie(name);
1513
+ if (idCookie) {
1514
+ getLogger().debug("Existing user id", idCookie);
1515
+ return idCookie;
1516
+ }
1517
+ var newId = generateId();
1518
+ getLogger().debug("New user id", newId);
1519
+ setCookie(name, newId, {
1520
+ domain: domain,
1521
+ secure: document.location.protocol !== "http:",
1522
+ maxAge: MAX_AGE_TEN_YEARS,
1523
+ });
1524
+ return newId;
1525
+ },
1526
+ };
1527
+ function ensurePrefix(prefix, str) {
1528
+ if (!str) {
1529
+ return str;
1530
+ }
1531
+ return (str === null || str === void 0 ? void 0 : str.length) > 0 && str.indexOf(prefix) !== 0 ? prefix + str : str;
1532
+ }
1533
+ function cutPostfix(postfixes, str) {
1534
+ for (var _i = 0, _a = typeof postfixes === "string"
1535
+ ? [postfixes]
1536
+ : postfixes; _i < _a.length; _i++) {
1537
+ var postfix = _a[_i];
1538
+ while (str && str.length > 0 && str.charAt(str.length - 1) === postfix) {
1539
+ str = str.substring(0, str.length - 1);
1540
+ }
1541
+ }
1542
+ return str;
1543
+ }
1544
+ function httpApi(req, res, opts) {
1545
+ if (opts === void 0) { opts = {}; }
1546
+ var header = function (req, name) {
1547
+ var vals = req.headers[name.toLowerCase()];
1548
+ if (!vals) {
1549
+ return undefined;
1550
+ }
1551
+ if (typeof vals === "string") {
1552
+ return vals;
1553
+ }
1554
+ else if (vals.length > 0) {
1555
+ return vals.join(",");
1556
+ }
1557
+ };
1558
+ return {
1559
+ getAnonymousId: function (_a) {
1560
+ var name = _a.name, domain = _a.domain;
1561
+ if (opts === null || opts === void 0 ? void 0 : opts.disableCookies) {
1562
+ return "";
1563
+ }
1564
+ var cookie = parseCookieString(req.headers["cookie"])[name];
1565
+ if (!cookie) {
1566
+ var cookieOpts = {
1567
+ maxAge: 31622400 * 10,
1568
+ httpOnly: false,
1569
+ };
1570
+ if (domain) {
1571
+ cookieOpts.domain = domain;
1572
+ }
1573
+ var newId = generateId();
1574
+ res.setHeader("Set-Cookie", serializeCookie(name, newId, cookieOpts));
1575
+ return newId;
1576
+ }
1577
+ else {
1578
+ return cookie;
1579
+ }
1580
+ },
1581
+ getSourceIp: function () {
1582
+ var ip = header(req, "x-forwarded-for") ||
1583
+ header(req, "x-real-ip") ||
1584
+ req.socket.remoteAddress;
1585
+ return ip && ip.split(",")[0].trim();
1586
+ },
1587
+ describeClient: function () {
1588
+ var url = req.url
1589
+ ? new URL(req.url, req.url.startsWith("http") ? undefined : "http://localhost")
1590
+ : {};
1591
+ var requestHost = header(req, "x-forwarded-host") || header(req, "host") || url.hostname;
1592
+ var proto = cutPostfix([":", "/"], header(req, "x-forwarded-proto") || url.protocol);
1593
+ var query = ensurePrefix("?", url.search);
1594
+ var path = ensurePrefix("/", url.pathname);
1595
+ return {
1596
+ doc_encoding: "",
1597
+ doc_host: requestHost,
1598
+ doc_path: req.url,
1599
+ doc_search: query,
1600
+ page_title: "",
1601
+ referer: header(req, "referrer"),
1602
+ screen_resolution: "",
1603
+ url: "".concat(proto, "://").concat(requestHost).concat(path || "").concat(query || ""),
1604
+ user_agent: req.headers["user-agent"],
1605
+ user_language: req.headers["accept-language"] &&
1606
+ req.headers["accept-language"].split(",")[0],
1607
+ vp_size: "",
1608
+ };
1609
+ },
1610
+ };
1611
+ }
1612
+ var emptyEnv = {
1613
+ getSourceIp: function () { return undefined; },
1614
+ describeClient: function () { return ({}); },
1615
+ getAnonymousId: function () { return ""; },
1616
+ };
1617
+ /**
1618
+ * Dictionary of supported environments
1619
+ */
1620
+ var envs = {
1621
+ httpApi: httpApi,
1622
+ nextjsApi: httpApi,
1623
+ // fetchApi: fetchApi,
1624
+ // nextjsMiddleware: fetchApi,
1625
+ browser: function () { return browserEnv; },
1626
+ express: httpApi,
1627
+ empty: function () { return emptyEnv; },
1628
+ };
1629
+ var xmlHttpTransport = function (url, jsonPayload, additionalHeaders, handler) {
1630
+ if (handler === void 0) { handler = function (code, body) {
1631
+ }; }
1632
+ var req = new window.XMLHttpRequest();
1633
+ return new Promise(function (resolve, reject) {
1634
+ req.onerror = function (e) {
1635
+ getLogger().error("Failed to send payload to ".concat(url, ": ").concat((e === null || e === void 0 ? void 0 : e.message) || "unknown error"), jsonPayload, e);
1636
+ handler(-1, {});
1637
+ reject(new Error("Failed to send JSON. See console logs"));
1638
+ };
1639
+ req.onload = function () {
1640
+ if (req.status !== 200) {
1641
+ handler(req.status, {});
1642
+ getLogger().warn("Failed to send data to ".concat(url, " (#").concat(req.status, " - ").concat(req.statusText, ")"), jsonPayload);
1643
+ reject(new Error("Failed to send JSON. Error code: ".concat(req.status, ". See logs for details")));
1644
+ }
1645
+ else {
1646
+ handler(req.status, req.responseText);
1647
+ }
1648
+ resolve();
1649
+ };
1650
+ req.open("POST", url);
1651
+ req.setRequestHeader("Content-Type", "application/json");
1652
+ Object.entries(additionalHeaders || {}).forEach(function (_a) {
1653
+ var key = _a[0], val = _a[1];
1654
+ return req.setRequestHeader(key, val);
1655
+ });
1656
+ req.send(jsonPayload);
1657
+ getLogger().debug("sending json", jsonPayload);
1658
+ });
1659
+ };
1660
+ var fetchTransport = function (fetch) {
1661
+ return function (url, jsonPayload, additionalHeaders, handler) {
1662
+ if (handler === void 0) { handler = function (code, body) {
1663
+ }; }
1664
+ return __awaiter(void 0, void 0, void 0, function () {
1665
+ var res, e_1, resJson, text, contentType, e_2;
1666
+ var _a, _b;
1667
+ return __generator(this, function (_c) {
1668
+ switch (_c.label) {
1669
+ case 0:
1670
+ _c.trys.push([0, 2, , 3]);
1671
+ return [4 /*yield*/, fetch(url, {
1672
+ method: "POST",
1673
+ headers: __assign({ Accept: "application/json", "Content-Type": "application/json" }, (additionalHeaders || {})),
1674
+ body: jsonPayload,
1675
+ })];
1676
+ case 1:
1677
+ res = _c.sent();
1678
+ return [3 /*break*/, 3];
1679
+ case 2:
1680
+ e_1 = _c.sent();
1681
+ getLogger().error("Failed to send data to ".concat(url, ": ").concat((e_1 === null || e_1 === void 0 ? void 0 : e_1.message) || "unknown error"), jsonPayload, e_1);
1682
+ handler(-1, {});
1683
+ return [2 /*return*/];
1684
+ case 3:
1685
+ if (res.status !== 200) {
1686
+ getLogger().warn("Failed to send data to ".concat(url, " (#").concat(res.status, " - ").concat(res.statusText, ")"), jsonPayload);
1687
+ handler(res.status, {});
1688
+ return [2 /*return*/];
1689
+ }
1690
+ resJson = {};
1691
+ text = "";
1692
+ contentType = (_b = (_a = res.headers) === null || _a === void 0 ? void 0 : _a.get('Content-Type')) !== null && _b !== void 0 ? _b : "";
1693
+ _c.label = 4;
1694
+ case 4:
1695
+ _c.trys.push([4, 6, , 7]);
1696
+ return [4 /*yield*/, res.text()];
1697
+ case 5:
1698
+ text = _c.sent();
1699
+ resJson = JSON.parse(text);
1700
+ return [3 /*break*/, 7];
1701
+ case 6:
1702
+ e_2 = _c.sent();
1703
+ getLogger().error("Failed to parse ".concat(url, " response. Content-type: ").concat(contentType, " text: ").concat(text), e_2);
1704
+ return [3 /*break*/, 7];
1705
+ case 7:
1706
+ try {
1707
+ handler(res.status, resJson);
1708
+ }
1709
+ catch (e) {
1710
+ getLogger().error("Failed to handle ".concat(url, " response. Content-type: ").concat(contentType, " text: ").concat(text), e);
1711
+ }
1712
+ return [2 /*return*/];
1713
+ }
1714
+ });
1715
+ });
1716
+ };
1717
+ };
1718
+ var UsermavenClientImpl = /** @class */ (function () {
1719
+ function UsermavenClientImpl() {
1720
+ this.userProperties = {};
1721
+ this.groupProperties = {};
1722
+ this.permanentProperties = {
1723
+ globalProps: {},
1724
+ propsPerEvent: {},
1725
+ };
1726
+ this.cookieDomain = "";
1727
+ this.trackingHost = "";
1728
+ this.idCookieName = "";
1729
+ this.randomizeUrl = false;
1730
+ this.apiKey = "";
1731
+ this.initialized = false;
1732
+ this._3pCookies = {};
1733
+ this.cookiePolicy = "keep";
1734
+ this.ipPolicy = "keep";
1735
+ this.beaconApi = false;
1736
+ this.transport = xmlHttpTransport;
1737
+ this.customHeaders = function () { return ({}); };
1738
+ this.queue = new MemoryQueue();
1739
+ this.maxSendAttempts = 4;
1740
+ this.retryTimeout = [500, 1e12];
1741
+ this.flushing = false;
1742
+ this.attempt = 1;
1743
+ this.propertyBlacklist = [];
1744
+ // public persistence?: UserMavenPersistence;
1745
+ // public sessionManager?: SessionIdManager;
1746
+ this.__autocapture_enabled = false;
1747
+ // private anonymousId: string = '';
1748
+ // Fallback tracking host
1749
+ this.trackingHostFallback = "https://events.usermaven.com" ;
1750
+ }
1751
+ // Used for session + autocapture
1752
+ UsermavenClientImpl.prototype.get_config = function (prop_name) {
1753
+ return this.config ? this.config[prop_name] : null;
1754
+ };
1755
+ UsermavenClientImpl.prototype.id = function (props, doNotSendEvent) {
1756
+ this.userProperties = __assign(__assign({}, this.userProperties), props);
1757
+ getLogger().debug("Usermaven user identified", props);
1758
+ if (this.userIdPersistence) {
1759
+ this.userIdPersistence.save(props);
1760
+ }
1761
+ else {
1762
+ getLogger().warn("Id() is called before initialization");
1763
+ }
1764
+ if (!doNotSendEvent) {
1765
+ return this.track("user_identify", {});
1766
+ }
1767
+ else {
1768
+ return Promise.resolve();
1769
+ }
1770
+ };
1771
+ UsermavenClientImpl.prototype.group = function (props, doNotSendEvent) {
1772
+ this.groupProperties = __assign(__assign({}, this.groupProperties), props);
1773
+ getLogger().debug("Usermaven group identified", props);
1774
+ if (this.userIdPersistence) {
1775
+ // Update the 'company' property in the user persistence
1776
+ this.userIdPersistence.save({ company: props });
1777
+ }
1778
+ else {
1779
+ getLogger().warn("Group() is called before initialization");
1780
+ }
1781
+ if (!doNotSendEvent) {
1782
+ return this.track("group", {});
1783
+ }
1784
+ else {
1785
+ return Promise.resolve();
1786
+ }
1787
+ };
1788
+ UsermavenClientImpl.prototype.reset = function (resetAnonId) {
1789
+ if (this.userIdPersistence) {
1790
+ this.userIdPersistence.delete();
1791
+ }
1792
+ if (this.propsPersistance) {
1793
+ this.propsPersistance.delete();
1794
+ }
1795
+ if (resetAnonId) {
1796
+ var idCookie = getCookie(this.idCookieName);
1797
+ if (idCookie) {
1798
+ getLogger().debug("Removing id cookie", idCookie);
1799
+ setCookie(this.idCookieName, "", {
1800
+ domain: this.cookieDomain,
1801
+ expires: new Date(0),
1802
+ });
1803
+ }
1804
+ }
1805
+ return Promise.resolve();
1806
+ };
1807
+ UsermavenClientImpl.prototype.rawTrack = function (payload) {
1808
+ return this.sendJson(payload);
1809
+ };
1810
+ UsermavenClientImpl.prototype.makeEvent = function (event_type, src, payload) {
1811
+ var _a;
1812
+ var env = payload.env, payloadData = __rest(payload, ["env"]);
1813
+ if (!env) {
1814
+ env = isWindowAvailable() ? envs.browser() : envs.empty();
1815
+ }
1816
+ this.restoreId();
1817
+ var context = this.getCtx(env);
1818
+ var persistentProps = __assign(__assign({}, this.permanentProperties.globalProps), ((_a = this.permanentProperties.propsPerEvent[event_type]) !== null && _a !== void 0 ? _a : {}));
1819
+ var base = __assign({ api_key: this.apiKey, src: src, event_type: event_type }, payloadData);
1820
+ var sourceIp = env.getSourceIp();
1821
+ if (sourceIp) {
1822
+ base["source_ip"] = sourceIp;
1823
+ }
1824
+ return this.compatMode
1825
+ ? __assign(__assign(__assign({}, persistentProps), { eventn_ctx: context }), base) : __assign(__assign(__assign({}, persistentProps), context), base);
1826
+ };
1827
+ UsermavenClientImpl.prototype._send3p = function (sourceType, object, type) {
1828
+ var eventType = "3rdparty";
1829
+ if (type && type !== "") {
1830
+ eventType = type;
1831
+ }
1832
+ var e = this.makeEvent(eventType, sourceType, {
1833
+ src_payload: object,
1834
+ });
1835
+ return this.sendJson(e);
1836
+ };
1837
+ UsermavenClientImpl.prototype.sendJson = function (json) {
1838
+ return __awaiter(this, void 0, Promise, function () {
1839
+ var umExclusionState;
1840
+ return __generator(this, function (_a) {
1841
+ switch (_a.label) {
1842
+ case 0:
1843
+ umExclusionState = getUmExclusionState();
1844
+ if (!!umExclusionState) return [3 /*break*/, 3];
1845
+ if (!(this.maxSendAttempts > 1)) return [3 /*break*/, 1];
1846
+ this.queue.push([json, 0]);
1847
+ this.scheduleFlush(0);
1848
+ return [3 /*break*/, 3];
1849
+ case 1: return [4 /*yield*/, this.doSendJson(json)];
1850
+ case 2:
1851
+ _a.sent();
1852
+ _a.label = 3;
1853
+ case 3: return [2 /*return*/];
1854
+ }
1855
+ });
1856
+ });
1857
+ };
1858
+ UsermavenClientImpl.prototype.doSendJson = function (json) {
1859
+ var _this = this;
1860
+ var cookiePolicy = this.cookiePolicy !== "keep" ? "&cookie_policy=".concat(this.cookiePolicy) : "";
1861
+ var ipPolicy = this.ipPolicy !== "keep" ? "&ip_policy=".concat(this.ipPolicy) : "";
1862
+ var urlPrefix = isWindowAvailable() ? "/api/v1/event" : "/api/v1/s2s/event";
1863
+ var url = "".concat(this.trackingHost).concat(urlPrefix, "?token=").concat(this.apiKey).concat(cookiePolicy).concat(ipPolicy);
1864
+ if (this.randomizeUrl) {
1865
+ url = "".concat(this.trackingHost, "/api.").concat(generateRandom(), "?p_").concat(generateRandom(), "=").concat(this.apiKey).concat(cookiePolicy).concat(ipPolicy);
1866
+ }
1867
+ var jsonString = JSON.stringify(json);
1868
+ getLogger().debug("Sending payload to ".concat(url), jsonString);
1869
+ return this.transport(url, jsonString, this.customHeaders(), function (code, body) {
1870
+ return _this.postHandle(code, body);
1871
+ });
1872
+ };
1873
+ UsermavenClientImpl.prototype.scheduleFlush = function (timeout) {
1874
+ var _this = this;
1875
+ if (this.flushing) {
1876
+ return;
1877
+ }
1878
+ this.flushing = true;
1879
+ if (typeof timeout === "undefined") {
1880
+ var random = Math.random() + 1;
1881
+ var factor = Math.pow(2, this.attempt++);
1882
+ timeout = Math.min(this.retryTimeout[0] * random * factor, this.retryTimeout[1]);
1883
+ }
1884
+ getLogger().debug("Scheduling event queue flush in ".concat(timeout, " ms."));
1885
+ setTimeout(function () { return _this.flush(); }, timeout);
1886
+ };
1887
+ UsermavenClientImpl.prototype.flush = function () {
1888
+ return __awaiter(this, void 0, Promise, function () {
1889
+ var queue;
1890
+ var _a;
1891
+ var _this = this;
1892
+ return __generator(this, function (_b) {
1893
+ switch (_b.label) {
1894
+ case 0:
1895
+ if (isWindowAvailable() && !window.navigator.onLine) {
1896
+ this.flushing = false;
1897
+ this.scheduleFlush();
1898
+ }
1899
+ queue = this.queue.flush();
1900
+ this.flushing = false;
1901
+ if (queue.length === 0) {
1902
+ return [2 /*return*/];
1903
+ }
1904
+ _b.label = 1;
1905
+ case 1:
1906
+ _b.trys.push([1, 3, , 4]);
1907
+ return [4 /*yield*/, this.doSendJson(queue.map(function (el) { return el[0]; }))];
1908
+ case 2:
1909
+ _b.sent();
1910
+ this.attempt = 1;
1911
+ getLogger().debug("Successfully flushed ".concat(queue.length, " events from queue"));
1912
+ return [3 /*break*/, 4];
1913
+ case 3:
1914
+ _b.sent();
1915
+ // In case of failing custom domain (trackingHost), we will replace it with default domain (trackingHostFallback)
1916
+ if (this.trackingHost !== this.trackingHostFallback) {
1917
+ getLogger().debug("Using fallback tracking host ".concat(this.trackingHostFallback, " instead of ").concat(this.trackingHost, " on ").concat(VERSION_INFO.env));
1918
+ this.trackingHost = this.trackingHostFallback;
1919
+ }
1920
+ queue = queue.map(function (el) { return [el[0], el[1] + 1]; }).filter(function (el) {
1921
+ if (el[1] >= _this.maxSendAttempts) {
1922
+ getLogger().error("Dropping queued event after ".concat(el[1], " attempts since max send attempts ").concat(_this.maxSendAttempts, " reached. See logs for details"));
1923
+ return false;
1924
+ }
1925
+ return true;
1926
+ });
1927
+ if (queue.length > 0) {
1928
+ (_a = this.queue).push.apply(_a, queue);
1929
+ this.scheduleFlush();
1930
+ }
1931
+ else {
1932
+ this.attempt = 1;
1933
+ }
1934
+ return [3 /*break*/, 4];
1935
+ case 4: return [2 /*return*/];
1936
+ }
1937
+ });
1938
+ });
1939
+ };
1940
+ UsermavenClientImpl.prototype.postHandle = function (status, response) {
1941
+ if (this.cookiePolicy === "strict" || this.cookiePolicy === "comply") {
1942
+ if (status === 200) {
1943
+ var data = response;
1944
+ if (typeof response === "string") {
1945
+ data = JSON.parse(response);
1946
+ }
1947
+ if (!data["delete_cookie"]) {
1948
+ return;
1949
+ }
1950
+ }
1951
+ this.userIdPersistence.delete();
1952
+ this.propsPersistance.delete();
1953
+ deleteCookie(this.idCookieName);
1954
+ }
1955
+ if (status === 200) {
1956
+ var data = response;
1957
+ if (typeof response === "string" && response.length > 0) {
1958
+ data = JSON.parse(response);
1959
+ var extras = data["jitsu_sdk_extras"];
1960
+ if (extras && extras.length > 0) {
1961
+ var isWindow = isWindowAvailable();
1962
+ if (!isWindow) {
1963
+ getLogger().error("Tags destination supported only in browser environment");
1964
+ }
1965
+ else {
1966
+ for (var _i = 0, extras_1 = extras; _i < extras_1.length; _i++) {
1967
+ var _a = extras_1[_i], type = _a.type, id = _a.id, value = _a.value;
1968
+ if (type === "tag") {
1969
+ var tag = document.createElement("div");
1970
+ tag.id = id;
1971
+ insertAndExecute(tag, value);
1972
+ if (tag.childElementCount > 0) {
1973
+ document.body.appendChild(tag);
1974
+ }
1975
+ }
1976
+ }
1977
+ }
1978
+ }
1979
+ }
1980
+ }
1981
+ };
1982
+ UsermavenClientImpl.prototype.getCtx = function (env) {
1983
+ var now = new Date();
1984
+ var props = env.describeClient() || {};
1985
+ var user = __assign({}, this.userProperties);
1986
+ var company = user['company'] || {};
1987
+ delete user['company'];
1988
+ var payload = __assign(__assign({ event_id: "", user: __assign({ anonymous_id: this.cookiePolicy !== "strict"
1989
+ ? env.getAnonymousId({
1990
+ name: this.idCookieName,
1991
+ domain: this.cookieDomain,
1992
+ })
1993
+ : "" }, user), ids: this._getIds(), utc_time: reformatDate(now.toISOString()), local_tz_offset: now.getTimezoneOffset() }, props), getDataFromParams(parseQuery(props.doc_search)));
1994
+ // id and name attributes will be checked on backend
1995
+ if (Object.keys(company).length) {
1996
+ payload['company'] = company;
1997
+ }
1998
+ return payload;
1999
+ };
2000
+ UsermavenClientImpl.prototype._getIds = function () {
2001
+ if (!isWindowAvailable()) {
2002
+ return {};
2003
+ }
2004
+ var cookies = getCookies(false);
2005
+ var res = {};
2006
+ for (var _i = 0, _a = Object.entries(cookies); _i < _a.length; _i++) {
2007
+ var _b = _a[_i], key = _b[0], value = _b[1];
2008
+ if (this._3pCookies[key]) {
2009
+ res[key.charAt(0) == "_" ? key.substr(1) : key] = value;
2010
+ }
2011
+ }
2012
+ return res;
2013
+ };
2014
+ UsermavenClientImpl.prototype.pathMatches = function (wildcardPath, docUrl) {
2015
+ var actualPath = new URL(docUrl).pathname;
2016
+ return actualPath.match(new RegExp('^' + wildcardPath.trim().replace(/\*\*/g, '.*').replace(/([^\.])\*/g, '$1[^\\s\/]*') + '\/?$'));
2017
+ };
2018
+ UsermavenClientImpl.prototype.track = function (type, payload) {
2019
+ var _this = this;
2020
+ var data = payload || {};
2021
+ getLogger().debug("track event of type", type, data);
2022
+ var env = isWindowAvailable() ? envs.browser() : envs.empty();
2023
+ var context = this.getCtx(env);
2024
+ // Check if the page is not excluded.
2025
+ if (this.config && this.config.exclude && this.config.exclude.length > 1 && (context === null || context === void 0 ? void 0 : context.url)) {
2026
+ var excludeList = this.config.exclude.split(',');
2027
+ // check if the current page is in the exclude list
2028
+ if (excludeList.some(function (excludePage) { return _this.pathMatches(excludePage.trim(), context === null || context === void 0 ? void 0 : context.url); })) {
2029
+ getLogger().debug("Page is excluded from tracking");
2030
+ return;
2031
+ }
2032
+ }
2033
+ var p = payload || {};
2034
+ // All custom events and scroll event will have event_attributes
2035
+ if (type !== "$autocapture" && type !== "user_identify" && type !== "pageview" && type !== "$pageleave") {
2036
+ p = {
2037
+ event_attributes: payload,
2038
+ };
2039
+ }
2040
+ var e = this.makeEvent(type, this.compatMode ? "eventn" : "usermaven", p);
2041
+ return this.sendJson(e);
2042
+ };
2043
+ UsermavenClientImpl.prototype.init = function (options) {
2044
+ var _this = this;
2045
+ var _a, _b, _c, _d;
2046
+ if (isWindowAvailable() && !options.force_use_fetch) {
2047
+ if (options.fetch) {
2048
+ getLogger().warn("Custom fetch implementation is provided to Usermaven. However, it will be ignored since Usermaven runs in browser");
2049
+ }
2050
+ this.transport = this.beaconApi ? beaconTransport : xmlHttpTransport;
2051
+ }
2052
+ else {
2053
+ if (!options.fetch && !globalThis.fetch) {
2054
+ throw new Error("Usermaven runs in Node environment. However, neither UsermavenOptions.fetch is provided, nor global fetch function is defined. \n" +
2055
+ "Please, provide custom fetch implementation. You can get it via node-fetch package");
2056
+ }
2057
+ this.transport = fetchTransport(options.fetch || globalThis.fetch);
2058
+ }
2059
+ if (options.custom_headers &&
2060
+ typeof options.custom_headers === "function") {
2061
+ this.customHeaders = options.custom_headers;
2062
+ }
2063
+ else if (options.custom_headers) {
2064
+ this.customHeaders = function () {
2065
+ return options.custom_headers;
2066
+ };
2067
+ }
2068
+ if (options.tracking_host === "echo") {
2069
+ getLogger().warn('jitsuClient is configured with "echo" transport. Outgoing requests will be written to console');
2070
+ this.transport = echoTransport;
2071
+ }
2072
+ if (options.ip_policy) {
2073
+ this.ipPolicy = options.ip_policy;
2074
+ }
2075
+ if (options.cookie_policy) {
2076
+ this.cookiePolicy = options.cookie_policy;
2077
+ }
2078
+ if (options.privacy_policy === "strict") {
2079
+ this.ipPolicy = "strict";
2080
+ this.cookiePolicy = "strict";
2081
+ }
2082
+ if (options.use_beacon_api && navigator.sendBeacon) {
2083
+ this.beaconApi = true;
2084
+ }
2085
+ //can't handle delete cookie response when beacon api
2086
+ if (this.cookiePolicy === "comply" && this.beaconApi) {
2087
+ this.cookiePolicy = "strict";
2088
+ }
2089
+ if (options.log_level) {
2090
+ setRootLogLevel(options.log_level);
2091
+ }
2092
+ this.initialOptions = options;
2093
+ getLogger().debug("Initializing Usemaven Tracker tracker", options, USERMAVEN_VERSION);
2094
+ if (!options.key) {
2095
+ getLogger().error("Can't initialize Usemaven, key property is not set");
2096
+ return;
2097
+ }
2098
+ this.compatMode =
2099
+ options.compat_mode === undefined
2100
+ ? defaultCompatMode
2101
+ : !!options.compat_mode;
2102
+ this.cookieDomain = options.cookie_domain || getCookieDomain();
2103
+ this.trackingHost = getHostWithProtocol(options["tracking_host"] || "t.usermaven.com");
2104
+ this.randomizeUrl = options.randomize_url || false;
2105
+ this.apiKey = options.key;
2106
+ this.idCookieName = options.cookie_name || "__eventn_id_".concat(options.key);
2107
+ if (this.cookiePolicy === "strict") {
2108
+ this.propsPersistance = new NoPersistence();
2109
+ }
2110
+ else {
2111
+ this.propsPersistance = isWindowAvailable()
2112
+ ? new CookiePersistence(this.cookieDomain, this.idCookieName + "_props")
2113
+ : new NoPersistence();
2114
+ }
2115
+ if (this.cookiePolicy === "strict") {
2116
+ this.userIdPersistence = new NoPersistence();
2117
+ }
2118
+ else {
2119
+ this.userIdPersistence = isWindowAvailable()
2120
+ ? new CookiePersistence(this.cookieDomain, this.idCookieName + "_usr")
2121
+ : new NoPersistence();
2122
+ }
2123
+ if (this.propsPersistance) {
2124
+ var restored = this.propsPersistance.restore();
2125
+ if (restored) {
2126
+ this.permanentProperties = restored;
2127
+ this.permanentProperties.globalProps = (_a = restored.globalProps) !== null && _a !== void 0 ? _a : {};
2128
+ this.permanentProperties.propsPerEvent = (_b = restored.propsPerEvent) !== null && _b !== void 0 ? _b : {};
2129
+ }
2130
+ getLogger().debug("Restored persistent properties", this.permanentProperties);
2131
+ }
2132
+ this.propertyBlacklist = options.property_blacklist && options.property_blacklist.length > 0 ? options.property_blacklist : [];
2133
+ // // Added these configuration for session management + autocapture
2134
+ var defaultConfig = {
2135
+ autocapture: false,
2136
+ properties_string_max_length: null,
2137
+ property_blacklist: [],
2138
+ sanitize_properties: null
2139
+ };
2140
+ this.config = _extend({}, defaultConfig, options || {}, this.config || {}, { token: this.apiKey });
2141
+ getLogger().debug('Default Configuration', this.config);
2142
+ // this.manageSession(this.config);
2143
+ this.manageAutoCapture(this.config);
2144
+ if (options.capture_3rd_party_cookies === false) {
2145
+ this._3pCookies = {};
2146
+ }
2147
+ else {
2148
+ (options.capture_3rd_party_cookies || [
2149
+ "_ga",
2150
+ "_fbp",
2151
+ "_ym_uid",
2152
+ "ajs_user_id",
2153
+ "ajs_anonymous_id",
2154
+ ]).forEach(function (name) { return (_this._3pCookies[name] = true); });
2155
+ }
2156
+ if (options.ga_hook) {
2157
+ getLogger().warn("GA event interceptor isn't supported anymore");
2158
+ }
2159
+ if (options.segment_hook) {
2160
+ interceptSegmentCalls(this);
2161
+ }
2162
+ if (isWindowAvailable()) {
2163
+ if (!options.disable_event_persistence) {
2164
+ this.queue = new LocalStorageQueue("jitsu-event-queue");
2165
+ this.scheduleFlush(0);
2166
+ }
2167
+ window.addEventListener("beforeunload", function () { return _this.flush(); });
2168
+ }
2169
+ this.retryTimeout = [
2170
+ (_c = options.min_send_timeout) !== null && _c !== void 0 ? _c : this.retryTimeout[0],
2171
+ (_d = options.max_send_timeout) !== null && _d !== void 0 ? _d : this.retryTimeout[1],
2172
+ ];
2173
+ if (!!options.max_send_attempts) {
2174
+ this.maxSendAttempts = options.max_send_attempts;
2175
+ }
2176
+ this.initialized = true;
2177
+ };
2178
+ UsermavenClientImpl.prototype.interceptAnalytics = function (analytics) {
2179
+ var _this = this;
2180
+ var interceptor = function (chain) {
2181
+ var _a;
2182
+ try {
2183
+ var payload = __assign({}, chain.payload);
2184
+ getLogger().debug("Intercepted segment payload", payload.obj);
2185
+ var integration = chain.integrations["Segment.io"];
2186
+ if (integration && integration.analytics) {
2187
+ var analyticsOriginal = integration.analytics;
2188
+ if (typeof analyticsOriginal.user === "function" &&
2189
+ analyticsOriginal.user() &&
2190
+ typeof analyticsOriginal.user().id === "function") {
2191
+ payload.obj.userId = analyticsOriginal.user().id();
2192
+ }
2193
+ }
2194
+ if ((_a = payload === null || payload === void 0 ? void 0 : payload.obj) === null || _a === void 0 ? void 0 : _a.timestamp) {
2195
+ payload.obj.sentAt = payload.obj.timestamp;
2196
+ }
2197
+ var type = chain.payload.type();
2198
+ if (type === "track") {
2199
+ type = chain.payload.event();
2200
+ }
2201
+ _this._send3p("ajs", payload, type);
2202
+ }
2203
+ catch (e) {
2204
+ getLogger().warn("Failed to send an event", e);
2205
+ }
2206
+ chain.next(chain.payload);
2207
+ };
2208
+ if (typeof analytics.addSourceMiddleware === "function") {
2209
+ //analytics is fully initialized
2210
+ getLogger().debug("Analytics.js is initialized, calling addSourceMiddleware");
2211
+ analytics.addSourceMiddleware(interceptor);
2212
+ }
2213
+ else {
2214
+ getLogger().debug("Analytics.js is not initialized, pushing addSourceMiddleware to callstack");
2215
+ analytics.push(["addSourceMiddleware", interceptor]);
2216
+ }
2217
+ analytics["__en_intercepted"] = true;
2218
+ };
2219
+ UsermavenClientImpl.prototype.restoreId = function () {
2220
+ if (this.userIdPersistence) {
2221
+ var props = this.userIdPersistence.restore();
2222
+ if (props) {
2223
+ this.userProperties = __assign(__assign({}, props), this.userProperties);
2224
+ }
2225
+ }
2226
+ };
2227
+ UsermavenClientImpl.prototype.set = function (properties, opts) {
2228
+ var _a;
2229
+ var eventType = opts === null || opts === void 0 ? void 0 : opts.eventType;
2230
+ var persist = (opts === null || opts === void 0 ? void 0 : opts.persist) === undefined || (opts === null || opts === void 0 ? void 0 : opts.persist);
2231
+ if (eventType !== undefined) {
2232
+ var current = (_a = this.permanentProperties.propsPerEvent[eventType]) !== null && _a !== void 0 ? _a : {};
2233
+ this.permanentProperties.propsPerEvent[eventType] = __assign(__assign({}, current), properties);
2234
+ }
2235
+ else {
2236
+ this.permanentProperties.globalProps = __assign(__assign({}, this.permanentProperties.globalProps), properties);
2237
+ }
2238
+ if (this.propsPersistance && persist) {
2239
+ this.propsPersistance.save(this.permanentProperties);
2240
+ }
2241
+ };
2242
+ UsermavenClientImpl.prototype.unset = function (propertyName, opts) {
2243
+ requireWindow();
2244
+ var eventType = opts === null || opts === void 0 ? void 0 : opts.eventType;
2245
+ var persist = (opts === null || opts === void 0 ? void 0 : opts.persist) === undefined || (opts === null || opts === void 0 ? void 0 : opts.persist);
2246
+ if (!eventType) {
2247
+ delete this.permanentProperties.globalProps[propertyName];
2248
+ }
2249
+ else if (this.permanentProperties.propsPerEvent[eventType]) {
2250
+ delete this.permanentProperties.propsPerEvent[eventType][propertyName];
2251
+ }
2252
+ if (this.propsPersistance && persist) {
2253
+ this.propsPersistance.save(this.permanentProperties);
2254
+ }
2255
+ };
2256
+ /**
2257
+ * Manage auto-capturing
2258
+ * @param options
2259
+ */
2260
+ UsermavenClientImpl.prototype.manageAutoCapture = function (options) {
2261
+ getLogger().debug("Auto Capture Status: ", this.config['autocapture']);
2262
+ this.__autocapture_enabled = this.config['autocapture'];
2263
+ if (!this.__autocapture_enabled) {
2264
+ return;
2265
+ }
2266
+ var num_buckets = 100;
2267
+ var num_enabled_buckets = 100;
2268
+ if (!autocapture.enabledForProject(this.apiKey, num_buckets, num_enabled_buckets)) {
2269
+ this.config['autocapture'] = false;
2270
+ this.__autocapture_enabled = false;
2271
+ getLogger().debug('Not in active bucket: disabling Automatic Event Collection.');
2272
+ }
2273
+ else if (!autocapture.isBrowserSupported()) {
2274
+ this.config['autocapture'] = false;
2275
+ this.__autocapture_enabled = false;
2276
+ getLogger().debug('Disabling Automatic Event Collection because this browser is not supported');
2277
+ }
2278
+ else {
2279
+ getLogger().debug('Autocapture enabled...');
2280
+ autocapture.init(this, options);
2281
+ }
2282
+ };
2283
+ /**
2284
+ * Capture an event. This is the most important and
2285
+ * frequently used usermaven function.
2286
+ *
2287
+ * ### Usage:
2288
+ * usermaven.capture('Registered', {'Gender': 'Male', 'Age': 21}, {});
2289
+ *
2290
+ * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
2291
+ * @param {Object} [properties] A set of properties to include with the event you're sending. These describe the user who did the event or details about the event itself.
2292
+ * @param {Object} [options] Optional configuration for this capture request.
2293
+ * @param {String} [options.transport] Transport method for network request ('XHR' or 'sendBeacon').
2294
+ */
2295
+ UsermavenClientImpl.prototype.capture = function (event_name, properties) {
2296
+ var _a, _b;
2297
+ if (properties === void 0) { properties = {}; }
2298
+ if (!this.initialized) {
2299
+ console.error('Trying to capture event before initialization');
2300
+ return;
2301
+ }
2302
+ if (_isUndefined(event_name) || typeof event_name !== 'string') {
2303
+ console.error('No event name provided to usermaven.capture');
2304
+ return;
2305
+ }
2306
+ // if (_.isBlockedUA(userAgent)) {
2307
+ // return
2308
+ // }
2309
+ var data = {
2310
+ event: event_name + (properties['$event_type'] ? '_' + properties['$event_type'] : ''),
2311
+ properties: this._calculate_event_properties(event_name, properties),
2312
+ };
2313
+ data = _copyAndTruncateStrings(data, this.get_config('properties_string_max_length'));
2314
+ // send event if there is a tagname available
2315
+ if ((_b = (_a = data.properties) === null || _a === void 0 ? void 0 : _a.autocapture_attributes) === null || _b === void 0 ? void 0 : _b.tag_name) {
2316
+ this.track("$autocapture", data.properties);
2317
+ // this.track(data.event, data.properties)
2318
+ }
2319
+ // send event if the event is $scroll
2320
+ if (event_name === '$scroll') {
2321
+ this.track(event_name, data.properties);
2322
+ }
2323
+ };
2324
+ UsermavenClientImpl.prototype._calculate_event_properties = function (event_name, event_properties) {
2325
+ var _a, _b;
2326
+ // set defaults
2327
+ var properties = event_properties || {};
2328
+ if (event_name === '$snapshot' || event_name === '$scroll') {
2329
+ return properties;
2330
+ }
2331
+ if (_isArray(this.propertyBlacklist)) {
2332
+ _each(this.propertyBlacklist, function (blacklisted_prop) {
2333
+ delete properties[blacklisted_prop];
2334
+ });
2335
+ }
2336
+ else {
2337
+ console.error('Invalid value for property_blacklist config: ' + this.propertyBlacklist);
2338
+ }
2339
+ // assign first element from $elements only
2340
+ var attributes = {};
2341
+ var elements = properties['$elements'] || [];
2342
+ if (elements.length) {
2343
+ attributes = elements[0];
2344
+ }
2345
+ properties['autocapture_attributes'] = attributes;
2346
+ properties['autocapture_attributes']["el_text"] = (_a = properties['autocapture_attributes']["$el_text"]) !== null && _a !== void 0 ? _a : "";
2347
+ properties['autocapture_attributes']["event_type"] = (_b = properties["$event_type"]) !== null && _b !== void 0 ? _b : "";
2348
+ ['$ce_version', "$event_type", "$initial_referrer", "$initial_referring_domain", "$referrer", "$referring_domain", "$elements"].forEach(function (key) {
2349
+ delete properties[key];
2350
+ });
2351
+ // TODO: later remove this from the autotrack code.
2352
+ delete properties['autocapture_attributes']["$el_text"];
2353
+ delete properties['autocapture_attributes']["nth_child"];
2354
+ delete properties['autocapture_attributes']["nth_of_type"];
2355
+ return properties;
2356
+ };
2357
+ return UsermavenClientImpl;
2358
+ }());
2359
+ function interceptSegmentCalls(t) {
2360
+ var win = window;
2361
+ if (!win.analytics) {
2362
+ win.analytics = [];
2363
+ }
2364
+ t.interceptAnalytics(win.analytics);
2365
+ }
2366
+
2367
+ function createClient(params) {
2368
+ return usermavenClient(params);
2369
+ }
2370
+
2371
+ function useUsermaven() {
2372
+ const client = useContext(UsermavenContext);
2373
+ if (!client) {
2374
+ throw new Error("Before calling useUsermaven() hook, please wrap your component into <JitsuProvider />. Read more in https://usermaven.com/docs/integrations/next");
2375
+ }
2376
+ const id = useCallback((userData, doNotSendEvent) => client === null || client === void 0 ? void 0 : client.id(userData, doNotSendEvent), [client]);
2377
+ const trackPageView = useCallback(() => client === null || client === void 0 ? void 0 : client.track('pageview'), [client]);
2378
+ const track = useCallback((typeName, payload) => client === null || client === void 0 ? void 0 : client.track(typeName, payload), [client]);
2379
+ const rawTrack = useCallback((payload) => client === null || client === void 0 ? void 0 : client.rawTrack(payload), [client]);
2380
+ const interceptAnalytics = useCallback((analytics) => client === null || client === void 0 ? void 0 : client.interceptAnalytics(analytics), [client]);
2381
+ return Object.assign(Object.assign({}, client), { id,
2382
+ track,
2383
+ trackPageView,
2384
+ rawTrack,
2385
+ interceptAnalytics });
2386
+ }
2387
+
2388
+ function usePageView(usermaven, opts = {}) {
2389
+ const router = useRouter();
2390
+ useEffect(() => {
2391
+ const handleRouteChange = () => {
2392
+ if (opts.before) {
2393
+ opts.before(usermaven);
2394
+ }
2395
+ usermaven.track((opts === null || opts === void 0 ? void 0 : opts.typeName) || 'pageview', opts.payload);
2396
+ };
2397
+ handleRouteChange();
2398
+ router.events.on('routeChangeComplete', handleRouteChange);
2399
+ return () => {
2400
+ router.events.off('routeChangeComplete', handleRouteChange);
2401
+ };
2402
+ }, [router.events, usermaven.track, opts.payload, opts.before]);
2403
+ return usermaven;
2404
+ }
2405
+
2406
+ /*!
2407
+ * cookie
2408
+ * Copyright(c) 2012-2014 Roman Shtylman
2409
+ * Copyright(c) 2015 Douglas Christopher Wilson
2410
+ * MIT Licensed
2411
+ */
2412
+ var serialize_1 = serialize;
2413
+
2414
+ /**
2415
+ * Module variables.
2416
+ * @private
2417
+ */
2418
+
2419
+ var __toString = Object.prototype.toString;
2420
+
2421
+ /**
2422
+ * RegExp to match field-content in RFC 7230 sec 3.2
2423
+ *
2424
+ * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
2425
+ * field-vchar = VCHAR / obs-text
2426
+ * obs-text = %x80-FF
2427
+ */
2428
+
2429
+ var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
2430
+
2431
+ /**
2432
+ * Serialize data into a cookie header.
2433
+ *
2434
+ * Serialize the a name value pair into a cookie string suitable for
2435
+ * http headers. An optional options object specified cookie parameters.
2436
+ *
2437
+ * serialize('foo', 'bar', { httpOnly: true })
2438
+ * => "foo=bar; httpOnly"
2439
+ *
2440
+ * @param {string} name
2441
+ * @param {string} val
2442
+ * @param {object} [options]
2443
+ * @return {string}
2444
+ * @public
2445
+ */
2446
+
2447
+ function serialize(name, val, options) {
2448
+ var opt = options || {};
2449
+ var enc = opt.encode || encode;
2450
+
2451
+ if (typeof enc !== 'function') {
2452
+ throw new TypeError('option encode is invalid');
2453
+ }
2454
+
2455
+ if (!fieldContentRegExp.test(name)) {
2456
+ throw new TypeError('argument name is invalid');
2457
+ }
2458
+
2459
+ var value = enc(val);
2460
+
2461
+ if (value && !fieldContentRegExp.test(value)) {
2462
+ throw new TypeError('argument val is invalid');
2463
+ }
2464
+
2465
+ var str = name + '=' + value;
2466
+
2467
+ if (null != opt.maxAge) {
2468
+ var maxAge = opt.maxAge - 0;
2469
+
2470
+ if (isNaN(maxAge) || !isFinite(maxAge)) {
2471
+ throw new TypeError('option maxAge is invalid')
2472
+ }
2473
+
2474
+ str += '; Max-Age=' + Math.floor(maxAge);
2475
+ }
2476
+
2477
+ if (opt.domain) {
2478
+ if (!fieldContentRegExp.test(opt.domain)) {
2479
+ throw new TypeError('option domain is invalid');
2480
+ }
2481
+
2482
+ str += '; Domain=' + opt.domain;
2483
+ }
2484
+
2485
+ if (opt.path) {
2486
+ if (!fieldContentRegExp.test(opt.path)) {
2487
+ throw new TypeError('option path is invalid');
2488
+ }
2489
+
2490
+ str += '; Path=' + opt.path;
2491
+ }
2492
+
2493
+ if (opt.expires) {
2494
+ var expires = opt.expires;
2495
+
2496
+ if (!isDate(expires) || isNaN(expires.valueOf())) {
2497
+ throw new TypeError('option expires is invalid');
2498
+ }
2499
+
2500
+ str += '; Expires=' + expires.toUTCString();
2501
+ }
2502
+
2503
+ if (opt.httpOnly) {
2504
+ str += '; HttpOnly';
2505
+ }
2506
+
2507
+ if (opt.secure) {
2508
+ str += '; Secure';
2509
+ }
2510
+
2511
+ if (opt.priority) {
2512
+ var priority = typeof opt.priority === 'string'
2513
+ ? opt.priority.toLowerCase()
2514
+ : opt.priority;
2515
+
2516
+ switch (priority) {
2517
+ case 'low':
2518
+ str += '; Priority=Low';
2519
+ break
2520
+ case 'medium':
2521
+ str += '; Priority=Medium';
2522
+ break
2523
+ case 'high':
2524
+ str += '; Priority=High';
2525
+ break
2526
+ default:
2527
+ throw new TypeError('option priority is invalid')
2528
+ }
2529
+ }
2530
+
2531
+ if (opt.sameSite) {
2532
+ var sameSite = typeof opt.sameSite === 'string'
2533
+ ? opt.sameSite.toLowerCase() : opt.sameSite;
2534
+
2535
+ switch (sameSite) {
2536
+ case true:
2537
+ str += '; SameSite=Strict';
2538
+ break;
2539
+ case 'lax':
2540
+ str += '; SameSite=Lax';
2541
+ break;
2542
+ case 'strict':
2543
+ str += '; SameSite=Strict';
2544
+ break;
2545
+ case 'none':
2546
+ str += '; SameSite=None';
2547
+ break;
2548
+ default:
2549
+ throw new TypeError('option sameSite is invalid');
2550
+ }
2551
+ }
2552
+
2553
+ return str;
2554
+ }
2555
+
2556
+ /**
2557
+ * URL-encode value.
2558
+ *
2559
+ * @param {string} str
2560
+ * @returns {string}
2561
+ */
2562
+
2563
+ function encode (val) {
2564
+ return encodeURIComponent(val)
2565
+ }
2566
+
2567
+ /**
2568
+ * Determine if value is a Date.
2569
+ *
2570
+ * @param {*} val
2571
+ * @private
2572
+ */
2573
+
2574
+ function isDate (val) {
2575
+ return __toString.call(val) === '[object Date]' ||
2576
+ val instanceof Date
2577
+ }
2578
+
2579
+ function middlewareEnv(req, res, opts = {}) {
2580
+ return {
2581
+ getAnonymousId({ name, domain }) {
2582
+ if (opts === null || opts === void 0 ? void 0 : opts.disableCookies) {
2583
+ return "";
2584
+ }
2585
+ const cookie = req.cookies[name];
2586
+ if (cookie) {
2587
+ return cookie;
2588
+ }
2589
+ const cookieOpts = {
2590
+ maxAge: 31622400 * 10,
2591
+ httpOnly: false,
2592
+ };
2593
+ if (domain) {
2594
+ cookieOpts.domain = domain;
2595
+ }
2596
+ let newId = Math.random().toString(36).substring(2, 12);
2597
+ res.headers.set("Set-Cookie", serialize_1(name, newId, cookieOpts));
2598
+ return newId;
2599
+ },
2600
+ getSourceIp() {
2601
+ let ip = req.headers.get("x-forwarded-for") || req.headers.get("x-real-ip") || req.ip;
2602
+ return ip && ip.split(",")[0].trim();
2603
+ },
2604
+ describeClient() {
2605
+ var _a;
2606
+ const requestHost = req.headers.get("x-forwarded-host") || req.headers.get("host") || req.nextUrl.hostname;
2607
+ const proto = req.headers.get("x-forwarded-proto") || ((_a = req.nextUrl.protocol) === null || _a === void 0 ? void 0 : _a.replace(":", ""));
2608
+ let query = req.nextUrl.search;
2609
+ let path = req.nextUrl.pathname;
2610
+ return {
2611
+ doc_encoding: "",
2612
+ doc_host: requestHost,
2613
+ doc_path: req.url,
2614
+ doc_search: query,
2615
+ page_title: "",
2616
+ referer: req.headers.get("referrer"),
2617
+ screen_resolution: "",
2618
+ url: `${proto}://${requestHost}${path || ""}${query || ""}`,
2619
+ user_agent: req.headers.get("user-agent"),
2620
+ user_language: req.headers.get("accept-language") && req.headers.get("accept-language").split(",")[0],
2621
+ vp_size: "",
2622
+ };
2623
+ },
2624
+ };
2625
+ }
2626
+
2627
+ export { UsermavenContext, JitsuProvider as UsermavenProvider, createClient, middlewareEnv, usePageView, useUsermaven };