@usermaven/sdk-js 1.4.4 → 1.5.1

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