@leanbase.com/js 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2,65 +2,2854 @@
2
2
 
3
3
  var core = require('@posthog/core');
4
4
 
5
- const version = '0.1.1';
5
+ const breaker = {};
6
+ const ArrayProto = Array.prototype;
7
+ const nativeForEach = ArrayProto.forEach;
8
+ const nativeIndexOf = ArrayProto.indexOf;
9
+ const win = typeof window !== 'undefined' ? window : undefined;
10
+ const global = typeof globalThis !== 'undefined' ? globalThis : win;
11
+ const navigator$1 = global?.navigator;
12
+ const document = global?.document;
13
+ const location = global?.location;
14
+ global?.fetch;
15
+ global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined;
16
+ global?.AbortController;
17
+ const userAgent = navigator$1?.userAgent;
18
+ function eachArray(obj, iterator, thisArg) {
19
+ if (core.isArray(obj)) {
20
+ if (nativeForEach && obj.forEach === nativeForEach) {
21
+ obj.forEach(iterator, thisArg);
22
+ } else if ('length' in obj && obj.length === +obj.length) {
23
+ for (let i = 0, l = obj.length; i < l; i++) {
24
+ if (i in obj && iterator.call(thisArg, obj[i], i) === breaker) {
25
+ return;
26
+ }
27
+ }
28
+ }
29
+ }
30
+ }
31
+ /**
32
+ * @param {*=} obj
33
+ * @param {function(...*)=} iterator
34
+ * @param {Object=} thisArg
35
+ */
36
+ function each(obj, iterator, thisArg) {
37
+ if (core.isNullish(obj)) {
38
+ return;
39
+ }
40
+ if (core.isArray(obj)) {
41
+ return eachArray(obj, iterator, thisArg);
42
+ }
43
+ if (core.isFormData(obj)) {
44
+ for (const pair of obj.entries()) {
45
+ if (iterator.call(thisArg, pair[1], pair[0]) === breaker) {
46
+ return;
47
+ }
48
+ }
49
+ return;
50
+ }
51
+ for (const key in obj) {
52
+ if (core.hasOwnProperty.call(obj, key)) {
53
+ if (iterator.call(thisArg, obj[key], key) === breaker) {
54
+ return;
55
+ }
56
+ }
57
+ }
58
+ }
59
+ const extend = function (obj, ...args) {
60
+ eachArray(args, function (source) {
61
+ for (const prop in source) {
62
+ if (source[prop] !== void 0) {
63
+ obj[prop] = source[prop];
64
+ }
65
+ }
66
+ });
67
+ return obj;
68
+ };
69
+ const extendArray = function (obj, ...args) {
70
+ eachArray(args, function (source) {
71
+ eachArray(source, function (item) {
72
+ obj.push(item);
73
+ });
74
+ });
75
+ return obj;
76
+ };
77
+ const include = function (obj, target) {
78
+ let found = false;
79
+ if (core.isNull(obj)) {
80
+ return found;
81
+ }
82
+ if (nativeIndexOf && obj.indexOf === nativeIndexOf) {
83
+ return obj.indexOf(target) != -1;
84
+ }
85
+ each(obj, function (value) {
86
+ if (found || (found = value === target)) {
87
+ return breaker;
88
+ }
89
+ return;
90
+ });
91
+ return found;
92
+ };
93
+ /**
94
+ * Object.entries() polyfill
95
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
96
+ */
97
+ function entries(obj) {
98
+ const ownProps = Object.keys(obj);
99
+ let i = ownProps.length;
100
+ const resArray = new Array(i); // preallocate the Array
101
+ while (i--) {
102
+ resArray[i] = [ownProps[i], obj[ownProps[i]]];
103
+ }
104
+ return resArray;
105
+ }
106
+ function addEventListener(element, event, callback, options) {
107
+ const {
108
+ capture = false,
109
+ passive = true
110
+ } = options ?? {};
111
+ // This is the only place where we are allowed to call this function
112
+ // because the whole idea is that we should be calling this instead of the built-in one
113
+ // eslint-disable-next-line posthog-js/no-add-event-listener
114
+ element?.addEventListener(event, callback, {
115
+ capture,
116
+ passive
117
+ });
118
+ }
119
+ const stripEmptyProperties = function (p) {
120
+ const ret = {};
121
+ each(p, function (v, k) {
122
+ if (core.isString(v) && v.length > 0 || core.isNumber(v)) {
123
+ ret[k] = v;
124
+ }
125
+ });
126
+ return ret;
127
+ };
128
+ const EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE = ['herokuapp.com', 'vercel.app', 'netlify.app'];
129
+ function isCrossDomainCookie(documentLocation) {
130
+ const hostname = documentLocation?.hostname;
131
+ if (!core.isString(hostname)) {
132
+ return false;
133
+ }
134
+ // split and slice isn't a great way to match arbitrary domains,
135
+ // but it's good enough for ensuring we only match herokuapp.com when it is the TLD
136
+ // for the hostname
137
+ const lastTwoParts = hostname.split('.').slice(-2).join('.');
138
+ for (const excluded of EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE) {
139
+ if (lastTwoParts === excluded) {
140
+ return false;
141
+ }
142
+ }
143
+ return true;
144
+ }
145
+ /**
146
+ * Deep copies an object.
147
+ * It handles cycles by replacing all references to them with `undefined`
148
+ * Also supports customizing native values
149
+ *
150
+ * @param value
151
+ * @param customizer
152
+ * @returns {{}|undefined|*}
153
+ */
154
+ function deepCircularCopy(value, customizer) {
155
+ const COPY_IN_PROGRESS_SET = new Set();
156
+ function internalDeepCircularCopy(value, key) {
157
+ if (value !== Object(value)) return customizer ? customizer(value, key) : value; // primitive value
158
+ if (COPY_IN_PROGRESS_SET.has(value)) return undefined;
159
+ COPY_IN_PROGRESS_SET.add(value);
160
+ let result;
161
+ if (core.isArray(value)) {
162
+ result = [];
163
+ eachArray(value, it => {
164
+ result.push(internalDeepCircularCopy(it));
165
+ });
166
+ } else {
167
+ result = {};
168
+ each(value, (val, key) => {
169
+ if (!COPY_IN_PROGRESS_SET.has(val)) {
170
+ result[key] = internalDeepCircularCopy(val, key);
171
+ }
172
+ });
173
+ }
174
+ return result;
175
+ }
176
+ return internalDeepCircularCopy(value);
177
+ }
178
+ function copyAndTruncateStrings(object, maxStringLength) {
179
+ return deepCircularCopy(object, value => {
180
+ if (core.isString(value) && !core.isNull(maxStringLength)) {
181
+ return value.slice(0, maxStringLength);
182
+ }
183
+ return value;
184
+ });
185
+ }
186
+
187
+ /*
188
+ * Constants
189
+ */
190
+ /* PROPERTY KEYS */
191
+ // This key is deprecated, but we want to check for it to see whether aliasing is allowed.
192
+ const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id';
193
+ const DISTINCT_ID = 'distinct_id';
194
+ const ALIAS_ID_KEY = '__alias';
195
+ const CAMPAIGN_IDS_KEY = '__cmpns';
196
+ const EVENT_TIMERS_KEY = '__timers';
197
+ const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side';
198
+ const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side';
199
+ const ERROR_TRACKING_SUPPRESSION_RULES = '$error_tracking_suppression_rules';
200
+ // @deprecated can be removed along with eager loaded replay
201
+ const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side';
202
+ const SESSION_ID = '$sesid';
203
+ const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled';
204
+ const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags';
205
+ const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features';
206
+ const PERSISTENCE_FEATURE_FLAG_DETAILS = '$feature_flag_details';
207
+ const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties';
208
+ const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties';
209
+ const SURVEYS = '$surveys';
210
+ const FLAG_CALL_REPORTED = '$flag_call_reported';
211
+ const USER_STATE = '$user_state';
212
+ const CLIENT_SESSION_PROPS = '$client_session_props';
213
+ const CAPTURE_RATE_LIMIT = '$capture_rate_limit';
214
+ /** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */
215
+ const INITIAL_CAMPAIGN_PARAMS = '$initial_campaign_params';
216
+ /** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */
217
+ const INITIAL_REFERRER_INFO = '$initial_referrer_info';
218
+ const INITIAL_PERSON_INFO = '$initial_person_info';
219
+ const ENABLE_PERSON_PROCESSING = '$epp';
220
+ const COOKIELESS_MODE_FLAG_PROPERTY = '$cookieless_mode';
221
+ // These are properties that are reserved and will not be automatically included in events
222
+ const PERSISTENCE_RESERVED_PROPERTIES = [PEOPLE_DISTINCT_ID_KEY, ALIAS_ID_KEY, CAMPAIGN_IDS_KEY, EVENT_TIMERS_KEY, SESSION_RECORDING_ENABLED_SERVER_SIDE, HEATMAPS_ENABLED_SERVER_SIDE, SESSION_ID, ENABLED_FEATURE_FLAGS, ERROR_TRACKING_SUPPRESSION_RULES, USER_STATE, PERSISTENCE_EARLY_ACCESS_FEATURES, PERSISTENCE_FEATURE_FLAG_DETAILS, STORED_GROUP_PROPERTIES_KEY, STORED_PERSON_PROPERTIES_KEY, SURVEYS, FLAG_CALL_REPORTED, CLIENT_SESSION_PROPS, CAPTURE_RATE_LIMIT, INITIAL_CAMPAIGN_PARAMS, INITIAL_REFERRER_INFO, ENABLE_PERSON_PROCESSING, INITIAL_PERSON_INFO,
223
+ // Ignore posthog persisted properties
224
+ core.PostHogPersistedProperty.Queue, core.PostHogPersistedProperty.FeatureFlagDetails, core.PostHogPersistedProperty.FlagsEndpointWasHit, core.PostHogPersistedProperty.AnonymousId, core.PostHogPersistedProperty.RemoteConfig, core.PostHogPersistedProperty.Surveys, core.PostHogPersistedProperty.FeatureFlags];
6
225
 
7
- // Simple logger with [Leanbase] prefix
226
+ /* eslint-disable no-console */
8
227
  const PREFIX = '[Leanbase]';
9
228
  const logger = {
10
229
  info: (...args) => {
11
230
  if (typeof console !== 'undefined') {
12
- // eslint-disable-next-line no-console
13
231
  console.log(PREFIX, ...args);
14
232
  }
15
- },
16
- warn: (...args) => {
17
- if (typeof console !== 'undefined') {
18
- // eslint-disable-next-line no-console
19
- console.warn(PREFIX, ...args);
233
+ },
234
+ warn: (...args) => {
235
+ if (typeof console !== 'undefined') {
236
+ console.warn(PREFIX, ...args);
237
+ }
238
+ },
239
+ error: (...args) => {
240
+ if (typeof console !== 'undefined') {
241
+ console.error(PREFIX, ...args);
242
+ }
243
+ },
244
+ critical: (...args) => {
245
+ if (typeof console !== 'undefined') {
246
+ console.error(PREFIX, 'CRITICAL:', ...args);
247
+ }
248
+ }
249
+ };
250
+
251
+ /**
252
+ * uuidv7: An experimental implementation of the proposed UUID Version 7
253
+ *
254
+ * @license Apache-2.0
255
+ * @copyright 2021-2023 LiosK
256
+ * @packageDocumentation
257
+ *
258
+ * from https://github.com/LiosK/uuidv7/blob/e501462ea3d23241de13192ceae726956f9b3b7d/src/index.ts
259
+ */
260
+ // polyfill for IE11
261
+ if (!Math.trunc) {
262
+ Math.trunc = function (v) {
263
+ return v < 0 ? Math.ceil(v) : Math.floor(v);
264
+ };
265
+ }
266
+ // polyfill for IE11
267
+ if (!Number.isInteger) {
268
+ Number.isInteger = function (value) {
269
+ return core.isNumber(value) && isFinite(value) && Math.floor(value) === value;
270
+ };
271
+ }
272
+ const DIGITS = '0123456789abcdef';
273
+ /** Represents a UUID as a 16-byte byte array. */
274
+ class UUID {
275
+ /** @param bytes - The 16-byte byte array representation. */
276
+ constructor(bytes) {
277
+ this.bytes = bytes;
278
+ if (bytes.length !== 16) {
279
+ throw new TypeError('not 128-bit length');
280
+ }
281
+ }
282
+ /**
283
+ * Builds a byte array from UUIDv7 field values.
284
+ *
285
+ * @param unixTsMs - A 48-bit `unix_ts_ms` field value.
286
+ * @param randA - A 12-bit `rand_a` field value.
287
+ * @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.
288
+ * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.
289
+ */
290
+ static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {
291
+ if (!Number.isInteger(unixTsMs) || !Number.isInteger(randA) || !Number.isInteger(randBHi) || !Number.isInteger(randBLo) || unixTsMs < 0 || randA < 0 || randBHi < 0 || randBLo < 0 || unixTsMs > 281474976710655 || randA > 0xfff || randBHi > 1073741823 || randBLo > 4294967295) {
292
+ throw new RangeError('invalid field value');
293
+ }
294
+ const bytes = new Uint8Array(16);
295
+ bytes[0] = unixTsMs / 2 ** 40;
296
+ bytes[1] = unixTsMs / 2 ** 32;
297
+ bytes[2] = unixTsMs / 2 ** 24;
298
+ bytes[3] = unixTsMs / 2 ** 16;
299
+ bytes[4] = unixTsMs / 2 ** 8;
300
+ bytes[5] = unixTsMs;
301
+ bytes[6] = 0x70 | randA >>> 8;
302
+ bytes[7] = randA;
303
+ bytes[8] = 0x80 | randBHi >>> 24;
304
+ bytes[9] = randBHi >>> 16;
305
+ bytes[10] = randBHi >>> 8;
306
+ bytes[11] = randBHi;
307
+ bytes[12] = randBLo >>> 24;
308
+ bytes[13] = randBLo >>> 16;
309
+ bytes[14] = randBLo >>> 8;
310
+ bytes[15] = randBLo;
311
+ return new UUID(bytes);
312
+ }
313
+ /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */
314
+ toString() {
315
+ let text = '';
316
+ for (let i = 0; i < this.bytes.length; i++) {
317
+ text = text + DIGITS.charAt(this.bytes[i] >>> 4) + DIGITS.charAt(this.bytes[i] & 0xf);
318
+ if (i === 3 || i === 5 || i === 7 || i === 9) {
319
+ text += '-';
320
+ }
321
+ }
322
+ if (text.length !== 36) {
323
+ // We saw one customer whose bundling code was mangling the UUID generation
324
+ // rather than accept a bad UUID, we throw an error here.
325
+ throw new Error('Invalid UUIDv7 was generated');
326
+ }
327
+ return text;
328
+ }
329
+ /** Creates an object from `this`. */
330
+ clone() {
331
+ return new UUID(this.bytes.slice(0));
332
+ }
333
+ /** Returns true if `this` is equivalent to `other`. */
334
+ equals(other) {
335
+ return this.compareTo(other) === 0;
336
+ }
337
+ /**
338
+ * Returns a negative integer, zero, or positive integer if `this` is less
339
+ * than, equal to, or greater than `other`, respectively.
340
+ */
341
+ compareTo(other) {
342
+ for (let i = 0; i < 16; i++) {
343
+ const diff = this.bytes[i] - other.bytes[i];
344
+ if (diff !== 0) {
345
+ return Math.sign(diff);
346
+ }
347
+ }
348
+ return 0;
349
+ }
350
+ }
351
+ /** Encapsulates the monotonic counter state. */
352
+ class V7Generator {
353
+ constructor() {
354
+ this._timestamp = 0;
355
+ this._counter = 0;
356
+ this._random = new DefaultRandom();
357
+ }
358
+ /**
359
+ * Generates a new UUIDv7 object from the current timestamp, or resets the
360
+ * generator upon significant timestamp rollback.
361
+ *
362
+ * This method returns monotonically increasing UUIDs unless the up-to-date
363
+ * timestamp is significantly (by ten seconds or more) smaller than the one
364
+ * embedded in the immediately preceding UUID. If such a significant clock
365
+ * rollback is detected, this method resets the generator and returns a new
366
+ * UUID based on the current timestamp.
367
+ */
368
+ generate() {
369
+ const value = this.generateOrAbort();
370
+ if (!core.isUndefined(value)) {
371
+ return value;
372
+ } else {
373
+ // reset state and resume
374
+ this._timestamp = 0;
375
+ const valueAfterReset = this.generateOrAbort();
376
+ if (core.isUndefined(valueAfterReset)) {
377
+ throw new Error('Could not generate UUID after timestamp reset');
378
+ }
379
+ return valueAfterReset;
380
+ }
381
+ }
382
+ /**
383
+ * Generates a new UUIDv7 object from the current timestamp, or returns
384
+ * `undefined` upon significant timestamp rollback.
385
+ *
386
+ * This method returns monotonically increasing UUIDs unless the up-to-date
387
+ * timestamp is significantly (by ten seconds or more) smaller than the one
388
+ * embedded in the immediately preceding UUID. If such a significant clock
389
+ * rollback is detected, this method aborts and returns `undefined`.
390
+ */
391
+ generateOrAbort() {
392
+ const MAX_COUNTER = 4398046511103;
393
+ const ROLLBACK_ALLOWANCE = 10000; // 10 seconds
394
+ const ts = Date.now();
395
+ if (ts > this._timestamp) {
396
+ this._timestamp = ts;
397
+ this._resetCounter();
398
+ } else if (ts + ROLLBACK_ALLOWANCE > this._timestamp) {
399
+ // go on with previous timestamp if new one is not much smaller
400
+ this._counter++;
401
+ if (this._counter > MAX_COUNTER) {
402
+ // increment timestamp at counter overflow
403
+ this._timestamp++;
404
+ this._resetCounter();
405
+ }
406
+ } else {
407
+ // abort if clock went backwards to unbearable extent
408
+ return undefined;
409
+ }
410
+ return UUID.fromFieldsV7(this._timestamp, Math.trunc(this._counter / 2 ** 30), this._counter & 2 ** 30 - 1, this._random.nextUint32());
411
+ }
412
+ /** Initializes the counter at a 42-bit random integer. */
413
+ _resetCounter() {
414
+ this._counter = this._random.nextUint32() * 0x400 + (this._random.nextUint32() & 0x3ff);
415
+ }
416
+ }
417
+ /** Stores `crypto.getRandomValues()` available in the environment. */
418
+ let getRandomValues = buffer => {
419
+ // fall back on Math.random() unless the flag is set to true
420
+ // TRICKY: don't use the isUndefined method here as can't pass the reference
421
+ if (typeof UUIDV7_DENY_WEAK_RNG !== 'undefined' && UUIDV7_DENY_WEAK_RNG) {
422
+ throw new Error('no cryptographically strong RNG available');
423
+ }
424
+ for (let i = 0; i < buffer.length; i++) {
425
+ buffer[i] = Math.trunc(Math.random() * 65536) * 65536 + Math.trunc(Math.random() * 65536);
426
+ }
427
+ return buffer;
428
+ };
429
+ // detect Web Crypto API
430
+ if (win && !core.isUndefined(win.crypto) && crypto.getRandomValues) {
431
+ getRandomValues = buffer => crypto.getRandomValues(buffer);
432
+ }
433
+ /**
434
+ * Wraps `crypto.getRandomValues()` and compatibles to enable buffering; this
435
+ * uses a small buffer by default to avoid unbearable throughput decline in some
436
+ * environments as well as the waste of time and space for unused values.
437
+ */
438
+ class DefaultRandom {
439
+ constructor() {
440
+ this._buffer = new Uint32Array(8);
441
+ this._cursor = Infinity;
442
+ }
443
+ nextUint32() {
444
+ if (this._cursor >= this._buffer.length) {
445
+ getRandomValues(this._buffer);
446
+ this._cursor = 0;
447
+ }
448
+ return this._buffer[this._cursor++];
449
+ }
450
+ }
451
+ let defaultGenerator;
452
+ /**
453
+ * Generates a UUIDv7 string.
454
+ *
455
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
456
+ * ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
457
+ */
458
+ const uuidv7 = () => uuidv7obj().toString();
459
+ /** Generates a UUIDv7 object. */
460
+ const uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
461
+
462
+ // we store the discovered subdomain in memory because it might be read multiple times
463
+ let firstNonPublicSubDomain = '';
464
+ /**
465
+ * Browsers don't offer a way to check if something is a public suffix
466
+ * e.g. `.com.au`, `.io`, `.org.uk`
467
+ *
468
+ * But they do reject cookies set on public suffixes
469
+ * Setting a cookie on `.co.uk` would mean it was sent for every `.co.uk` site visited
470
+ *
471
+ * So, we can use this to check if a domain is a public suffix
472
+ * by trying to set a cookie on a subdomain of the provided hostname
473
+ * until the browser accepts it
474
+ *
475
+ * inspired by https://github.com/AngusFu/browser-root-domain
476
+ */
477
+ function seekFirstNonPublicSubDomain(hostname, cookieJar = document) {
478
+ if (firstNonPublicSubDomain) {
479
+ return firstNonPublicSubDomain;
480
+ }
481
+ if (!cookieJar) {
482
+ return '';
483
+ }
484
+ if (['localhost', '127.0.0.1'].includes(hostname)) return '';
485
+ const list = hostname.split('.');
486
+ let len = Math.min(list.length, 8); // paranoia - we know this number should be small
487
+ const key = 'dmn_chk_' + uuidv7();
488
+ while (!firstNonPublicSubDomain && len--) {
489
+ const candidate = list.slice(len).join('.');
490
+ const candidateCookieValue = key + '=1;domain=.' + candidate + ';path=/';
491
+ // try to set cookie, include a short expiry in seconds since we'll check immediately
492
+ cookieJar.cookie = candidateCookieValue + ';max-age=3';
493
+ if (cookieJar.cookie.includes(key)) {
494
+ // the cookie was accepted by the browser, remove the test cookie
495
+ cookieJar.cookie = candidateCookieValue + ';max-age=0';
496
+ firstNonPublicSubDomain = candidate;
497
+ }
498
+ }
499
+ return firstNonPublicSubDomain;
500
+ }
501
+ const DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;
502
+ const originalCookieDomainFn = hostname => {
503
+ const matches = hostname.match(DOMAIN_MATCH_REGEX);
504
+ return matches ? matches[0] : '';
505
+ };
506
+ function chooseCookieDomain(hostname, cross_subdomain) {
507
+ if (cross_subdomain) {
508
+ // NOTE: Could we use this for cross domain tracking?
509
+ let matchedSubDomain = seekFirstNonPublicSubDomain(hostname);
510
+ if (!matchedSubDomain) {
511
+ const originalMatch = originalCookieDomainFn(hostname);
512
+ if (originalMatch !== matchedSubDomain) {
513
+ logger.info('Warning: cookie subdomain discovery mismatch', originalMatch, matchedSubDomain);
514
+ }
515
+ matchedSubDomain = originalMatch;
516
+ }
517
+ return matchedSubDomain ? '; domain=.' + matchedSubDomain : '';
518
+ }
519
+ return '';
520
+ }
521
+ // Methods partially borrowed from quirksmode.org/js/cookies.html
522
+ const cookieStore = {
523
+ _is_supported: () => !!document,
524
+ _error: function (msg) {
525
+ logger.error('cookieStore error: ' + msg);
526
+ },
527
+ _get: function (name) {
528
+ if (!document) {
529
+ return;
530
+ }
531
+ try {
532
+ const nameEQ = name + '=';
533
+ const ca = document.cookie.split(';').filter(x => x.length);
534
+ for (let i = 0; i < ca.length; i++) {
535
+ let c = ca[i];
536
+ while (c.charAt(0) == ' ') {
537
+ c = c.substring(1, c.length);
538
+ }
539
+ if (c.indexOf(nameEQ) === 0) {
540
+ return decodeURIComponent(c.substring(nameEQ.length, c.length));
541
+ }
542
+ }
543
+ } catch {}
544
+ return null;
545
+ },
546
+ _parse: function (name) {
547
+ let cookie;
548
+ try {
549
+ cookie = JSON.parse(cookieStore._get(name)) || {};
550
+ } catch {
551
+ // noop
552
+ }
553
+ return cookie;
554
+ },
555
+ _set: function (name, value, days, cross_subdomain, is_secure) {
556
+ if (!document) {
557
+ return;
558
+ }
559
+ try {
560
+ let expires = '',
561
+ secure = '';
562
+ const cdomain = chooseCookieDomain(document.location.hostname, cross_subdomain);
563
+ if (days) {
564
+ const date = new Date();
565
+ date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
566
+ expires = '; expires=' + date.toUTCString();
567
+ }
568
+ if (is_secure) {
569
+ secure = '; secure';
570
+ }
571
+ const new_cookie_val = name + '=' + encodeURIComponent(JSON.stringify(value)) + expires + '; SameSite=Lax; path=/' + cdomain + secure;
572
+ // 4096 bytes is the size at which some browsers (e.g. firefox) will not store a cookie, warn slightly before that
573
+ if (new_cookie_val.length > 4096 * 0.9) {
574
+ logger.warn('cookieStore warning: large cookie, len=' + new_cookie_val.length);
575
+ }
576
+ document.cookie = new_cookie_val;
577
+ return new_cookie_val;
578
+ } catch {
579
+ return;
580
+ }
581
+ },
582
+ _remove: function (name, cross_subdomain) {
583
+ if (!document?.cookie) {
584
+ return;
585
+ }
586
+ try {
587
+ cookieStore._set(name, '', -1, cross_subdomain);
588
+ } catch {
589
+ return;
590
+ }
591
+ }
592
+ };
593
+ let _localStorage_supported = null;
594
+ const localStore = {
595
+ _is_supported: function () {
596
+ if (!core.isNull(_localStorage_supported)) {
597
+ return _localStorage_supported;
598
+ }
599
+ let supported = true;
600
+ if (!core.isUndefined(win)) {
601
+ try {
602
+ const key = '__mplssupport__',
603
+ val = 'xyz';
604
+ localStore._set(key, val);
605
+ if (localStore._get(key) !== '"xyz"') {
606
+ supported = false;
607
+ }
608
+ localStore._remove(key);
609
+ } catch {
610
+ supported = false;
611
+ }
612
+ } else {
613
+ supported = false;
614
+ }
615
+ if (!supported) {
616
+ logger.error('localStorage unsupported; falling back to cookie store');
617
+ }
618
+ _localStorage_supported = supported;
619
+ return supported;
620
+ },
621
+ _error: function (msg) {
622
+ logger.error('localStorage error: ' + msg);
623
+ },
624
+ _get: function (name) {
625
+ try {
626
+ return win?.localStorage.getItem(name);
627
+ } catch (err) {
628
+ localStore._error(err);
629
+ }
630
+ return null;
631
+ },
632
+ _parse: function (name) {
633
+ try {
634
+ return JSON.parse(localStore._get(name)) || {};
635
+ } catch {
636
+ // noop
637
+ }
638
+ return null;
639
+ },
640
+ _set: function (name, value) {
641
+ try {
642
+ win?.localStorage.setItem(name, JSON.stringify(value));
643
+ } catch (err) {
644
+ localStore._error(err);
645
+ }
646
+ },
647
+ _remove: function (name) {
648
+ try {
649
+ win?.localStorage.removeItem(name);
650
+ } catch (err) {
651
+ localStore._error(err);
652
+ }
653
+ }
654
+ };
655
+ // Use localstorage for most data but still use cookie for COOKIE_PERSISTED_PROPERTIES
656
+ // This solves issues with cookies having too much data in them causing headers too large
657
+ // Also makes sure we don't have to send a ton of data to the server
658
+ const COOKIE_PERSISTED_PROPERTIES = [DISTINCT_ID, SESSION_ID, SESSION_RECORDING_IS_SAMPLED, ENABLE_PERSON_PROCESSING, INITIAL_PERSON_INFO];
659
+ const localPlusCookieStore = {
660
+ ...localStore,
661
+ _parse: function (name) {
662
+ try {
663
+ let cookieProperties = {};
664
+ try {
665
+ // See if there's a cookie stored with data.
666
+ cookieProperties = cookieStore._parse(name) || {};
667
+ } catch {}
668
+ const value = extend(cookieProperties, JSON.parse(localStore._get(name) || '{}'));
669
+ localStore._set(name, value);
670
+ return value;
671
+ } catch {
672
+ // noop
673
+ }
674
+ return null;
675
+ },
676
+ _set: function (name, value, days, cross_subdomain, is_secure, debug) {
677
+ try {
678
+ localStore._set(name, value, undefined, undefined, debug);
679
+ const cookiePersistedProperties = {};
680
+ COOKIE_PERSISTED_PROPERTIES.forEach(key => {
681
+ if (value[key]) {
682
+ cookiePersistedProperties[key] = value[key];
683
+ }
684
+ });
685
+ if (Object.keys(cookiePersistedProperties).length) {
686
+ cookieStore._set(name, cookiePersistedProperties, days, cross_subdomain, is_secure, debug);
687
+ }
688
+ } catch (err) {
689
+ localStore._error(err);
690
+ }
691
+ },
692
+ _remove: function (name, cross_subdomain) {
693
+ try {
694
+ win?.localStorage.removeItem(name);
695
+ cookieStore._remove(name, cross_subdomain);
696
+ } catch (err) {
697
+ localStore._error(err);
698
+ }
699
+ }
700
+ };
701
+ const memoryStorage = {};
702
+ // Storage that only lasts the length of the pageview if we don't want to use cookies
703
+ const memoryStore = {
704
+ _is_supported: function () {
705
+ return true;
706
+ },
707
+ _error: function (msg) {
708
+ logger.error('memoryStorage error: ' + msg);
709
+ },
710
+ _get: function (name) {
711
+ return memoryStorage[name] || null;
712
+ },
713
+ _parse: function (name) {
714
+ return memoryStorage[name] || null;
715
+ },
716
+ _set: function (name, value) {
717
+ memoryStorage[name] = value;
718
+ },
719
+ _remove: function (name) {
720
+ delete memoryStorage[name];
721
+ }
722
+ };
723
+ let sessionStorageSupported = null;
724
+ // Storage that only lasts the length of a tab/window. Survives page refreshes
725
+ const sessionStore = {
726
+ _is_supported: function () {
727
+ if (!core.isNull(sessionStorageSupported)) {
728
+ return sessionStorageSupported;
729
+ }
730
+ sessionStorageSupported = true;
731
+ if (!core.isUndefined(win)) {
732
+ try {
733
+ const key = '__support__',
734
+ val = 'xyz';
735
+ sessionStore._set(key, val);
736
+ if (sessionStore._get(key) !== '"xyz"') {
737
+ sessionStorageSupported = false;
738
+ }
739
+ sessionStore._remove(key);
740
+ } catch {
741
+ sessionStorageSupported = false;
742
+ }
743
+ } else {
744
+ sessionStorageSupported = false;
745
+ }
746
+ return sessionStorageSupported;
747
+ },
748
+ _error: function (msg) {
749
+ logger.error('sessionStorage error: ', msg);
750
+ },
751
+ _get: function (name) {
752
+ try {
753
+ return win?.sessionStorage.getItem(name);
754
+ } catch (err) {
755
+ sessionStore._error(err);
756
+ }
757
+ return null;
758
+ },
759
+ _parse: function (name) {
760
+ try {
761
+ return JSON.parse(sessionStore._get(name)) || null;
762
+ } catch {
763
+ // noop
764
+ }
765
+ return null;
766
+ },
767
+ _set: function (name, value) {
768
+ try {
769
+ win?.sessionStorage.setItem(name, JSON.stringify(value));
770
+ } catch (err) {
771
+ sessionStore._error(err);
772
+ }
773
+ },
774
+ _remove: function (name) {
775
+ try {
776
+ win?.sessionStorage.removeItem(name);
777
+ } catch (err) {
778
+ sessionStore._error(err);
779
+ }
780
+ }
781
+ };
782
+
783
+ /**
784
+ * IE11 doesn't support `new URL`
785
+ * so we can create an anchor element and use that to parse the URL
786
+ * there's a lot of overlap between HTMLHyperlinkElementUtils and URL
787
+ * meaning useful properties like `pathname` are available on both
788
+ */
789
+ const convertToURL = url => {
790
+ const location = document?.createElement('a');
791
+ if (core.isUndefined(location)) {
792
+ return null;
793
+ }
794
+ location.href = url;
795
+ return location;
796
+ };
797
+ // NOTE: Once we get rid of IE11/op_mini we can start using URLSearchParams
798
+ const getQueryParam = function (url, param) {
799
+ const withoutHash = url.split('#')[0] || '';
800
+ // Split only on the first ? to sort problem out for those with multiple ?s
801
+ // and then remove them
802
+ const queryParams = withoutHash.split(/\?(.*)/)[1] || '';
803
+ const cleanedQueryParams = queryParams.replace(/^\?+/g, '');
804
+ const queryParts = cleanedQueryParams.split('&');
805
+ let keyValuePair;
806
+ for (let i = 0; i < queryParts.length; i++) {
807
+ const parts = queryParts[i].split('=');
808
+ if (parts[0] === param) {
809
+ keyValuePair = parts;
810
+ break;
811
+ }
812
+ }
813
+ if (!core.isArray(keyValuePair) || keyValuePair.length < 2) {
814
+ return '';
815
+ } else {
816
+ let result = keyValuePair[1];
817
+ try {
818
+ result = decodeURIComponent(result);
819
+ } catch {
820
+ logger.error('Skipping decoding for malformed query param: ' + result);
821
+ }
822
+ return result.replace(/\+/g, ' ');
823
+ }
824
+ };
825
+ // replace any query params in the url with the provided mask value. Tries to keep the URL as instant as possible,
826
+ // including preserving malformed text in most cases
827
+ const maskQueryParams = function (url, maskedParams, mask) {
828
+ if (!url || !maskedParams || !maskedParams.length) {
829
+ return url;
830
+ }
831
+ const splitHash = url.split('#');
832
+ const withoutHash = splitHash[0] || '';
833
+ const hash = splitHash[1];
834
+ const splitQuery = withoutHash.split('?');
835
+ const queryString = splitQuery[1];
836
+ const urlWithoutQueryAndHash = splitQuery[0];
837
+ const queryParts = (queryString || '').split('&');
838
+ // use an array of strings rather than an object to preserve ordering and duplicates
839
+ const paramStrings = [];
840
+ for (let i = 0; i < queryParts.length; i++) {
841
+ const keyValuePair = queryParts[i].split('=');
842
+ if (!core.isArray(keyValuePair)) {
843
+ continue;
844
+ } else if (maskedParams.includes(keyValuePair[0])) {
845
+ paramStrings.push(keyValuePair[0] + '=' + mask);
846
+ } else {
847
+ paramStrings.push(queryParts[i]);
848
+ }
849
+ }
850
+ let result = urlWithoutQueryAndHash;
851
+ if (queryString != null) {
852
+ result += '?' + paramStrings.join('&');
853
+ }
854
+ if (hash != null) {
855
+ result += '#' + hash;
856
+ }
857
+ return result;
858
+ };
859
+
860
+ /**
861
+ * this device detection code is (at time of writing) about 3% of the size of the entire library
862
+ * this is mostly because the identifiers user in regexes and results can't be minified away since
863
+ * they have meaning
864
+ *
865
+ * so, there are some pre-uglifying choices in the code to help reduce the size
866
+ * e.g. many repeated strings are stored as variables and then old-fashioned concatenated together
867
+ *
868
+ * TL;DR here be dragons
869
+ */
870
+ const FACEBOOK = 'Facebook';
871
+ const MOBILE = 'Mobile';
872
+ const IOS = 'iOS';
873
+ const ANDROID = 'Android';
874
+ const TABLET = 'Tablet';
875
+ const ANDROID_TABLET = ANDROID + ' ' + TABLET;
876
+ const IPAD = 'iPad';
877
+ const APPLE = 'Apple';
878
+ const APPLE_WATCH = APPLE + ' Watch';
879
+ const SAFARI = 'Safari';
880
+ const BLACKBERRY = 'BlackBerry';
881
+ const SAMSUNG = 'Samsung';
882
+ const SAMSUNG_BROWSER = SAMSUNG + 'Browser';
883
+ const SAMSUNG_INTERNET = SAMSUNG + ' Internet';
884
+ const CHROME = 'Chrome';
885
+ const CHROME_OS = CHROME + ' OS';
886
+ const CHROME_IOS = CHROME + ' ' + IOS;
887
+ const INTERNET_EXPLORER = 'Internet Explorer';
888
+ const INTERNET_EXPLORER_MOBILE = INTERNET_EXPLORER + ' ' + MOBILE;
889
+ const OPERA = 'Opera';
890
+ const OPERA_MINI = OPERA + ' Mini';
891
+ const EDGE = 'Edge';
892
+ const MICROSOFT_EDGE = 'Microsoft ' + EDGE;
893
+ const FIREFOX = 'Firefox';
894
+ const FIREFOX_IOS = FIREFOX + ' ' + IOS;
895
+ const NINTENDO = 'Nintendo';
896
+ const PLAYSTATION = 'PlayStation';
897
+ const XBOX = 'Xbox';
898
+ const ANDROID_MOBILE = ANDROID + ' ' + MOBILE;
899
+ const MOBILE_SAFARI = MOBILE + ' ' + SAFARI;
900
+ const WINDOWS = 'Windows';
901
+ const WINDOWS_PHONE = WINDOWS + ' Phone';
902
+ const NOKIA = 'Nokia';
903
+ const OUYA = 'Ouya';
904
+ const GENERIC = 'Generic';
905
+ const GENERIC_MOBILE = GENERIC + ' ' + MOBILE.toLowerCase();
906
+ const GENERIC_TABLET = GENERIC + ' ' + TABLET.toLowerCase();
907
+ const KONQUEROR = 'Konqueror';
908
+ const BROWSER_VERSION_REGEX_SUFFIX = '(\\d+(\\.\\d+)?)';
909
+ const DEFAULT_BROWSER_VERSION_REGEX = new RegExp('Version/' + BROWSER_VERSION_REGEX_SUFFIX);
910
+ const XBOX_REGEX = new RegExp(XBOX, 'i');
911
+ const PLAYSTATION_REGEX = new RegExp(PLAYSTATION + ' \\w+', 'i');
912
+ const NINTENDO_REGEX = new RegExp(NINTENDO + ' \\w+', 'i');
913
+ const BLACKBERRY_REGEX = new RegExp(BLACKBERRY + '|PlayBook|BB10', 'i');
914
+ const windowsVersionMap = {
915
+ 'NT3.51': 'NT 3.11',
916
+ 'NT4.0': 'NT 4.0',
917
+ '5.0': '2000',
918
+ '5.1': 'XP',
919
+ '5.2': 'XP',
920
+ '6.0': 'Vista',
921
+ '6.1': '7',
922
+ '6.2': '8',
923
+ '6.3': '8.1',
924
+ '6.4': '10',
925
+ '10.0': '10'
926
+ };
927
+ /**
928
+ * Safari detection turns out to be complicated. For e.g. https://stackoverflow.com/a/29696509
929
+ * We can be slightly loose because some options have been ruled out (e.g. firefox on iOS)
930
+ * before this check is made
931
+ */
932
+ function isSafari(userAgent) {
933
+ return core.includes(userAgent, SAFARI) && !core.includes(userAgent, CHROME) && !core.includes(userAgent, ANDROID);
934
+ }
935
+ const safariCheck = (ua, vendor) => vendor && core.includes(vendor, APPLE) || isSafari(ua);
936
+ /**
937
+ * This function detects which browser is running this script.
938
+ * The order of the checks are important since many user agents
939
+ * include keywords used in later checks.
940
+ */
941
+ const detectBrowser = function (user_agent, vendor) {
942
+ vendor = vendor || ''; // vendor is undefined for at least IE9
943
+ if (core.includes(user_agent, ' OPR/') && core.includes(user_agent, 'Mini')) {
944
+ return OPERA_MINI;
945
+ } else if (core.includes(user_agent, ' OPR/')) {
946
+ return OPERA;
947
+ } else if (BLACKBERRY_REGEX.test(user_agent)) {
948
+ return BLACKBERRY;
949
+ } else if (core.includes(user_agent, 'IE' + MOBILE) || core.includes(user_agent, 'WPDesktop')) {
950
+ return INTERNET_EXPLORER_MOBILE;
951
+ }
952
+ // https://developer.samsung.com/internet/user-agent-string-format
953
+ else if (core.includes(user_agent, SAMSUNG_BROWSER)) {
954
+ return SAMSUNG_INTERNET;
955
+ } else if (core.includes(user_agent, EDGE) || core.includes(user_agent, 'Edg/')) {
956
+ return MICROSOFT_EDGE;
957
+ } else if (core.includes(user_agent, 'FBIOS')) {
958
+ return FACEBOOK + ' ' + MOBILE;
959
+ } else if (core.includes(user_agent, 'UCWEB') || core.includes(user_agent, 'UCBrowser')) {
960
+ return 'UC Browser';
961
+ } else if (core.includes(user_agent, 'CriOS')) {
962
+ return CHROME_IOS; // why not just Chrome?
963
+ } else if (core.includes(user_agent, 'CrMo')) {
964
+ return CHROME;
965
+ } else if (core.includes(user_agent, CHROME)) {
966
+ return CHROME;
967
+ } else if (core.includes(user_agent, ANDROID) && core.includes(user_agent, SAFARI)) {
968
+ return ANDROID_MOBILE;
969
+ } else if (core.includes(user_agent, 'FxiOS')) {
970
+ return FIREFOX_IOS;
971
+ } else if (core.includes(user_agent.toLowerCase(), KONQUEROR.toLowerCase())) {
972
+ return KONQUEROR;
973
+ } else if (safariCheck(user_agent, vendor)) {
974
+ return core.includes(user_agent, MOBILE) ? MOBILE_SAFARI : SAFARI;
975
+ } else if (core.includes(user_agent, FIREFOX)) {
976
+ return FIREFOX;
977
+ } else if (core.includes(user_agent, 'MSIE') || core.includes(user_agent, 'Trident/')) {
978
+ return INTERNET_EXPLORER;
979
+ } else if (core.includes(user_agent, 'Gecko')) {
980
+ return FIREFOX;
981
+ }
982
+ return '';
983
+ };
984
+ const versionRegexes = {
985
+ [INTERNET_EXPLORER_MOBILE]: [new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)],
986
+ [MICROSOFT_EDGE]: [new RegExp(EDGE + '?\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
987
+ [CHROME]: [new RegExp('(' + CHROME + '|CrMo)\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
988
+ [CHROME_IOS]: [new RegExp('CriOS\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
989
+ 'UC Browser': [new RegExp('(UCBrowser|UCWEB)\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
990
+ [SAFARI]: [DEFAULT_BROWSER_VERSION_REGEX],
991
+ [MOBILE_SAFARI]: [DEFAULT_BROWSER_VERSION_REGEX],
992
+ [OPERA]: [new RegExp('(' + OPERA + '|OPR)\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
993
+ [FIREFOX]: [new RegExp(FIREFOX + '\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
994
+ [FIREFOX_IOS]: [new RegExp('FxiOS\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
995
+ [KONQUEROR]: [new RegExp('Konqueror[:/]?' + BROWSER_VERSION_REGEX_SUFFIX, 'i')],
996
+ // not every blackberry user agent has the version after the name
997
+ [BLACKBERRY]: [new RegExp(BLACKBERRY + ' ' + BROWSER_VERSION_REGEX_SUFFIX), DEFAULT_BROWSER_VERSION_REGEX],
998
+ [ANDROID_MOBILE]: [new RegExp('android\\s' + BROWSER_VERSION_REGEX_SUFFIX, 'i')],
999
+ [SAMSUNG_INTERNET]: [new RegExp(SAMSUNG_BROWSER + '\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
1000
+ [INTERNET_EXPLORER]: [new RegExp('(rv:|MSIE )' + BROWSER_VERSION_REGEX_SUFFIX)],
1001
+ Mozilla: [new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)]
1002
+ };
1003
+ /**
1004
+ * This function detects which browser version is running this script,
1005
+ * parsing major and minor version (e.g., 42.1). User agent strings from:
1006
+ * http://www.useragentstring.com/pages/useragentstring.php
1007
+ *
1008
+ * `navigator.vendor` is passed in and used to help with detecting certain browsers
1009
+ * NB `navigator.vendor` is deprecated and not present in every browser
1010
+ */
1011
+ const detectBrowserVersion = function (userAgent, vendor) {
1012
+ const browser = detectBrowser(userAgent, vendor);
1013
+ const regexes = versionRegexes[browser];
1014
+ if (core.isUndefined(regexes)) {
1015
+ return null;
1016
+ }
1017
+ for (let i = 0; i < regexes.length; i++) {
1018
+ const regex = regexes[i];
1019
+ const matches = userAgent.match(regex);
1020
+ if (matches) {
1021
+ return parseFloat(matches[matches.length - 2]);
1022
+ }
1023
+ }
1024
+ return null;
1025
+ };
1026
+ // to avoid repeating regexes or calling them twice, we have an array of matches
1027
+ // the first regex that matches uses its matcher function to return the result
1028
+ const osMatchers = [[new RegExp(XBOX + '; ' + XBOX + ' (.*?)[);]', 'i'), match => {
1029
+ return [XBOX, match && match[1] || ''];
1030
+ }], [new RegExp(NINTENDO, 'i'), [NINTENDO, '']], [new RegExp(PLAYSTATION, 'i'), [PLAYSTATION, '']], [BLACKBERRY_REGEX, [BLACKBERRY, '']], [new RegExp(WINDOWS, 'i'), (_, user_agent) => {
1031
+ if (/Phone/.test(user_agent) || /WPDesktop/.test(user_agent)) {
1032
+ return [WINDOWS_PHONE, ''];
1033
+ }
1034
+ // not all JS versions support negative lookbehind, so we need two checks here
1035
+ if (new RegExp(MOBILE).test(user_agent) && !/IEMobile\b/.test(user_agent)) {
1036
+ return [WINDOWS + ' ' + MOBILE, ''];
1037
+ }
1038
+ const match = /Windows NT ([0-9.]+)/i.exec(user_agent);
1039
+ if (match && match[1]) {
1040
+ const version = match[1];
1041
+ let osVersion = windowsVersionMap[version] || '';
1042
+ if (/arm/i.test(user_agent)) {
1043
+ osVersion = 'RT';
1044
+ }
1045
+ return [WINDOWS, osVersion];
1046
+ }
1047
+ return [WINDOWS, ''];
1048
+ }], [/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/, match => {
1049
+ if (match && match[3]) {
1050
+ const versionParts = [match[3], match[4], match[5] || '0'];
1051
+ return [IOS, versionParts.join('.')];
1052
+ }
1053
+ return [IOS, ''];
1054
+ }], [/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i, match => {
1055
+ // e.g. Watch4,3/5.3.8 (16U680)
1056
+ let version = '';
1057
+ if (match && match.length >= 3) {
1058
+ version = core.isUndefined(match[2]) ? match[3] : match[2];
1059
+ }
1060
+ return ['watchOS', version];
1061
+ }], [new RegExp('(' + ANDROID + ' (\\d+)\\.(\\d+)\\.?(\\d+)?|' + ANDROID + ')', 'i'), match => {
1062
+ if (match && match[2]) {
1063
+ const versionParts = [match[2], match[3], match[4] || '0'];
1064
+ return [ANDROID, versionParts.join('.')];
1065
+ }
1066
+ return [ANDROID, ''];
1067
+ }], [/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i, match => {
1068
+ const result = ['Mac OS X', ''];
1069
+ if (match && match[1]) {
1070
+ const versionParts = [match[1], match[2], match[3] || '0'];
1071
+ result[1] = versionParts.join('.');
1072
+ }
1073
+ return result;
1074
+ }], [/Mac/i,
1075
+ // mop up a few non-standard UAs that should match mac
1076
+ ['Mac OS X', '']], [/CrOS/, [CHROME_OS, '']], [/Linux|debian/i, ['Linux', '']]];
1077
+ const detectOS = function (user_agent) {
1078
+ for (let i = 0; i < osMatchers.length; i++) {
1079
+ const [rgex, resultOrFn] = osMatchers[i];
1080
+ const match = rgex.exec(user_agent);
1081
+ const result = match && (core.isFunction(resultOrFn) ? resultOrFn(match, user_agent) : resultOrFn);
1082
+ if (result) {
1083
+ return result;
1084
+ }
1085
+ }
1086
+ return ['', ''];
1087
+ };
1088
+ const detectDevice = function (user_agent) {
1089
+ if (NINTENDO_REGEX.test(user_agent)) {
1090
+ return NINTENDO;
1091
+ } else if (PLAYSTATION_REGEX.test(user_agent)) {
1092
+ return PLAYSTATION;
1093
+ } else if (XBOX_REGEX.test(user_agent)) {
1094
+ return XBOX;
1095
+ } else if (new RegExp(OUYA, 'i').test(user_agent)) {
1096
+ return OUYA;
1097
+ } else if (new RegExp('(' + WINDOWS_PHONE + '|WPDesktop)', 'i').test(user_agent)) {
1098
+ return WINDOWS_PHONE;
1099
+ } else if (/iPad/.test(user_agent)) {
1100
+ return IPAD;
1101
+ } else if (/iPod/.test(user_agent)) {
1102
+ return 'iPod Touch';
1103
+ } else if (/iPhone/.test(user_agent)) {
1104
+ return 'iPhone';
1105
+ } else if (/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(user_agent)) {
1106
+ return APPLE_WATCH;
1107
+ } else if (BLACKBERRY_REGEX.test(user_agent)) {
1108
+ return BLACKBERRY;
1109
+ } else if (/(kobo)\s(ereader|touch)/i.test(user_agent)) {
1110
+ return 'Kobo';
1111
+ } else if (new RegExp(NOKIA, 'i').test(user_agent)) {
1112
+ return NOKIA;
1113
+ } else if (
1114
+ // Kindle Fire without Silk / Echo Show
1115
+ /(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(user_agent) ||
1116
+ // Kindle Fire HD
1117
+ /(kf[a-z]+)( bui|\)).+silk\//i.test(user_agent)) {
1118
+ return 'Kindle Fire';
1119
+ } else if (/(Android|ZTE)/i.test(user_agent)) {
1120
+ if (!new RegExp(MOBILE).test(user_agent) || /(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(user_agent)) {
1121
+ if (/pixel[\daxl ]{1,6}/i.test(user_agent) && !/pixel c/i.test(user_agent) || /(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(user_agent) || /lmy47v/i.test(user_agent) && !/QTAQZ3/i.test(user_agent)) {
1122
+ return ANDROID;
1123
+ }
1124
+ return ANDROID_TABLET;
1125
+ } else {
1126
+ return ANDROID;
1127
+ }
1128
+ } else if (new RegExp('(pda|' + MOBILE + ')', 'i').test(user_agent)) {
1129
+ return GENERIC_MOBILE;
1130
+ } else if (new RegExp(TABLET, 'i').test(user_agent) && !new RegExp(TABLET + ' pc', 'i').test(user_agent)) {
1131
+ return GENERIC_TABLET;
1132
+ } else {
1133
+ return '';
1134
+ }
1135
+ };
1136
+ const detectDeviceType = function (user_agent) {
1137
+ const device = detectDevice(user_agent);
1138
+ if (device === IPAD || device === ANDROID_TABLET || device === 'Kobo' || device === 'Kindle Fire' || device === GENERIC_TABLET) {
1139
+ return TABLET;
1140
+ } else if (device === NINTENDO || device === XBOX || device === PLAYSTATION || device === OUYA) {
1141
+ return 'Console';
1142
+ } else if (device === APPLE_WATCH) {
1143
+ return 'Wearable';
1144
+ } else if (device) {
1145
+ return MOBILE;
1146
+ } else {
1147
+ return 'Desktop';
1148
+ }
1149
+ };
1150
+
1151
+ var version = "0.1.3";
1152
+ var packageInfo = {
1153
+ version: version};
1154
+
1155
+ const Config = {
1156
+ LIB_VERSION: packageInfo.version
1157
+ };
1158
+
1159
+ const URL_REGEX_PREFIX = 'https?://(.*)';
1160
+ // CAMPAIGN_PARAMS and EVENT_TO_PERSON_PROPERTIES should be kept in sync with
1161
+ // https://github.com/PostHog/posthog/blob/master/plugin-server/src/utils/db/utils.ts#L60
1162
+ // The list of campaign parameters that could be considered personal data under e.g. GDPR.
1163
+ // These can be masked in URLs and properties before being sent to posthog.
1164
+ const PERSONAL_DATA_CAMPAIGN_PARAMS = ['gclid',
1165
+ // google ads
1166
+ 'gclsrc',
1167
+ // google ads 360
1168
+ 'dclid',
1169
+ // google display ads
1170
+ 'gbraid',
1171
+ // google ads, web to app
1172
+ 'wbraid',
1173
+ // google ads, app to web
1174
+ 'fbclid',
1175
+ // facebook
1176
+ 'msclkid',
1177
+ // microsoft
1178
+ 'twclid',
1179
+ // twitter
1180
+ 'li_fat_id',
1181
+ // linkedin
1182
+ 'igshid',
1183
+ // instagram
1184
+ 'ttclid',
1185
+ // tiktok
1186
+ 'rdt_cid',
1187
+ // reddit
1188
+ 'epik',
1189
+ // pinterest
1190
+ 'qclid',
1191
+ // quora
1192
+ 'sccid',
1193
+ // snapchat
1194
+ 'irclid',
1195
+ // impact
1196
+ '_kx' // klaviyo
1197
+ ];
1198
+ const CAMPAIGN_PARAMS = extendArray(['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'gad_source',
1199
+ // google ads source
1200
+ 'mc_cid' // mailchimp campaign id
1201
+ ], PERSONAL_DATA_CAMPAIGN_PARAMS);
1202
+ const MASKED = '<masked>';
1203
+ // Campaign params that can be read from the cookie store
1204
+ const COOKIE_CAMPAIGN_PARAMS = ['li_fat_id' // linkedin
1205
+ ];
1206
+ function getCampaignParams(customTrackedParams, maskPersonalDataProperties, customPersonalDataProperties) {
1207
+ if (!document) {
1208
+ return {};
1209
+ }
1210
+ const paramsToMask = maskPersonalDataProperties ? extendArray([], PERSONAL_DATA_CAMPAIGN_PARAMS, customPersonalDataProperties || []) : [];
1211
+ // Initially get campaign params from the URL
1212
+ const urlCampaignParams = _getCampaignParamsFromUrl(maskQueryParams(document.URL, paramsToMask, MASKED), customTrackedParams);
1213
+ // But we can also get some of them from the cookie store
1214
+ // For example: https://learn.microsoft.com/en-us/linkedin/marketing/conversions/enabling-first-party-cookies?view=li-lms-2025-05#reading-li_fat_id-from-cookies
1215
+ const cookieCampaignParams = _getCampaignParamsFromCookie();
1216
+ // Prefer the values found in the urlCampaignParams if possible
1217
+ // `extend` will override the values if found in the second argument
1218
+ return extend(cookieCampaignParams, urlCampaignParams);
1219
+ }
1220
+ function _getCampaignParamsFromUrl(url, customParams) {
1221
+ const campaign_keywords = CAMPAIGN_PARAMS.concat(customParams || []);
1222
+ const params = {};
1223
+ each(campaign_keywords, function (kwkey) {
1224
+ const kw = getQueryParam(url, kwkey);
1225
+ params[kwkey] = kw ? kw : null;
1226
+ });
1227
+ return params;
1228
+ }
1229
+ function _getCampaignParamsFromCookie() {
1230
+ const params = {};
1231
+ each(COOKIE_CAMPAIGN_PARAMS, function (kwkey) {
1232
+ const kw = cookieStore._get(kwkey);
1233
+ params[kwkey] = kw ? kw : null;
1234
+ });
1235
+ return params;
1236
+ }
1237
+ function _getSearchEngine(referrer) {
1238
+ if (!referrer) {
1239
+ return null;
1240
+ } else {
1241
+ if (referrer.search(URL_REGEX_PREFIX + 'google.([^/?]*)') === 0) {
1242
+ return 'google';
1243
+ } else if (referrer.search(URL_REGEX_PREFIX + 'bing.com') === 0) {
1244
+ return 'bing';
1245
+ } else if (referrer.search(URL_REGEX_PREFIX + 'yahoo.com') === 0) {
1246
+ return 'yahoo';
1247
+ } else if (referrer.search(URL_REGEX_PREFIX + 'duckduckgo.com') === 0) {
1248
+ return 'duckduckgo';
1249
+ } else {
1250
+ return null;
1251
+ }
1252
+ }
1253
+ }
1254
+ function _getSearchInfoFromReferrer(referrer) {
1255
+ const search = _getSearchEngine(referrer);
1256
+ const param = search != 'yahoo' ? 'q' : 'p';
1257
+ const ret = {};
1258
+ if (!core.isNull(search)) {
1259
+ ret['$search_engine'] = search;
1260
+ const keyword = document ? getQueryParam(document.referrer, param) : '';
1261
+ if (keyword.length) {
1262
+ ret['ph_keyword'] = keyword;
1263
+ }
1264
+ }
1265
+ return ret;
1266
+ }
1267
+ function getSearchInfo() {
1268
+ const referrer = document?.referrer;
1269
+ if (!referrer) {
1270
+ return {};
1271
+ }
1272
+ return _getSearchInfoFromReferrer(referrer);
1273
+ }
1274
+ function getBrowserLanguage() {
1275
+ return navigator.language ||
1276
+ // Any modern browser
1277
+ navigator.userLanguage // IE11
1278
+ ;
1279
+ }
1280
+ function getBrowserLanguagePrefix() {
1281
+ const lang = getBrowserLanguage();
1282
+ return typeof lang === 'string' ? lang.split('-')[0] : undefined;
1283
+ }
1284
+ function getReferrer() {
1285
+ return document?.referrer || '$direct';
1286
+ }
1287
+ function getReferringDomain() {
1288
+ if (!document?.referrer) {
1289
+ return '$direct';
1290
+ }
1291
+ return convertToURL(document.referrer)?.host || '$direct';
1292
+ }
1293
+ function getReferrerInfo() {
1294
+ return {
1295
+ $referrer: getReferrer(),
1296
+ $referring_domain: getReferringDomain()
1297
+ };
1298
+ }
1299
+ function getPersonInfo(maskPersonalDataProperties, customPersonalDataProperties) {
1300
+ const paramsToMask = maskPersonalDataProperties ? extendArray([], PERSONAL_DATA_CAMPAIGN_PARAMS, customPersonalDataProperties || []) : [];
1301
+ const url = location?.href.substring(0, 1000);
1302
+ // we're being a bit more economical with bytes here because this is stored in the cookie
1303
+ return {
1304
+ r: getReferrer().substring(0, 1000),
1305
+ u: url ? maskQueryParams(url, paramsToMask, MASKED) : undefined
1306
+ };
1307
+ }
1308
+ function getPersonPropsFromInfo(info) {
1309
+ const {
1310
+ r: referrer,
1311
+ u: url
1312
+ } = info;
1313
+ const referring_domain = referrer == null ? undefined : referrer == '$direct' ? '$direct' : convertToURL(referrer)?.host;
1314
+ const props = {
1315
+ $referrer: referrer,
1316
+ $referring_domain: referring_domain
1317
+ };
1318
+ if (url) {
1319
+ props['$current_url'] = url;
1320
+ const location = convertToURL(url);
1321
+ props['$host'] = location?.host;
1322
+ props['$pathname'] = location?.pathname;
1323
+ const campaignParams = _getCampaignParamsFromUrl(url);
1324
+ extend(props, campaignParams);
1325
+ }
1326
+ if (referrer) {
1327
+ const searchInfo = _getSearchInfoFromReferrer(referrer);
1328
+ extend(props, searchInfo);
1329
+ }
1330
+ return props;
1331
+ }
1332
+ function getInitialPersonPropsFromInfo(info) {
1333
+ const personProps = getPersonPropsFromInfo(info);
1334
+ const props = {};
1335
+ each(personProps, function (val, key) {
1336
+ props[`$initial_${core.stripLeadingDollar(key)}`] = val;
1337
+ });
1338
+ return props;
1339
+ }
1340
+ function getTimezone() {
1341
+ try {
1342
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
1343
+ } catch {
1344
+ return undefined;
1345
+ }
1346
+ }
1347
+ function getTimezoneOffset() {
1348
+ try {
1349
+ return new Date().getTimezoneOffset();
1350
+ } catch {
1351
+ return undefined;
1352
+ }
1353
+ }
1354
+ function getEventProperties(maskPersonalDataProperties, customPersonalDataProperties) {
1355
+ if (!userAgent) {
1356
+ return {};
1357
+ }
1358
+ const paramsToMask = maskPersonalDataProperties ? extendArray([], PERSONAL_DATA_CAMPAIGN_PARAMS, customPersonalDataProperties || []) : [];
1359
+ const [os_name, os_version] = detectOS(userAgent);
1360
+ return extend(stripEmptyProperties({
1361
+ $os: os_name,
1362
+ $os_version: os_version,
1363
+ $browser: detectBrowser(userAgent, navigator.vendor),
1364
+ $device: detectDevice(userAgent),
1365
+ $device_type: detectDeviceType(userAgent),
1366
+ $timezone: getTimezone(),
1367
+ $timezone_offset: getTimezoneOffset()
1368
+ }), {
1369
+ $current_url: maskQueryParams(location?.href, paramsToMask, MASKED),
1370
+ $host: location?.host,
1371
+ $pathname: location?.pathname,
1372
+ $raw_user_agent: userAgent.length > 1000 ? userAgent.substring(0, 997) + '...' : userAgent,
1373
+ $browser_version: detectBrowserVersion(userAgent, navigator.vendor),
1374
+ $browser_language: getBrowserLanguage(),
1375
+ $browser_language_prefix: getBrowserLanguagePrefix(),
1376
+ $screen_height: win?.screen.height,
1377
+ $screen_width: win?.screen.width,
1378
+ $viewport_height: win?.innerHeight,
1379
+ $viewport_width: win?.innerWidth,
1380
+ $lib: 'web',
1381
+ $lib_version: Config.LIB_VERSION,
1382
+ $insert_id: Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10),
1383
+ $time: Date.now() / 1000 // epoch time in seconds
1384
+ });
1385
+ }
1386
+
1387
+ /* eslint camelcase: "off" */
1388
+ const CASE_INSENSITIVE_PERSISTENCE_TYPES = ['cookie', 'localstorage', 'localstorage+cookie', 'sessionstorage', 'memory'];
1389
+ const parseName = config => {
1390
+ let token = '';
1391
+ if (config['token']) {
1392
+ token = config['token'].replace(/\+/g, 'PL').replace(/\//g, 'SL').replace(/=/g, 'EQ');
1393
+ }
1394
+ if (config['persistence_name']) {
1395
+ return config['persistence_name'];
1396
+ }
1397
+ return 'leanbase_' + token;
1398
+ };
1399
+ /**
1400
+ * Leanbase Persistence Object
1401
+ * @constructor
1402
+ */
1403
+ class LeanbasePersistence {
1404
+ /**
1405
+ * @param {LeanbaseConfig} config initial PostHog configuration
1406
+ * @param {boolean=} isDisabled should persistence be disabled (e.g. because of consent management)
1407
+ */
1408
+ constructor(config, isDisabled) {
1409
+ this._config = config;
1410
+ this.props = {};
1411
+ this._campaign_params_saved = false;
1412
+ this._name = parseName(config);
1413
+ this._storage = this._buildStorage(config);
1414
+ this.load();
1415
+ if (config.debug) {
1416
+ logger.info('Persistence loaded', config['persistence'], {
1417
+ ...this.props
1418
+ });
1419
+ }
1420
+ this.update_config(config, config, isDisabled);
1421
+ this.save();
1422
+ }
1423
+ /**
1424
+ * Returns whether persistence is disabled. Only available in SDKs > 1.257.1. Do not use on extensions, otherwise
1425
+ * it'll break backwards compatibility for any version before 1.257.1.
1426
+ */
1427
+ isDisabled() {
1428
+ return !!this._disabled;
1429
+ }
1430
+ _buildStorage(config) {
1431
+ if (CASE_INSENSITIVE_PERSISTENCE_TYPES.indexOf(config['persistence'].toLowerCase()) === -1) {
1432
+ logger.info('Unknown persistence type ' + config['persistence'] + '; falling back to localStorage+cookie');
1433
+ config['persistence'] = 'localStorage+cookie';
1434
+ }
1435
+ let store;
1436
+ const storage_type = config['persistence'].toLowerCase();
1437
+ if (storage_type === 'localstorage' && localStore._is_supported()) {
1438
+ store = localStore;
1439
+ } else if (storage_type === 'localstorage+cookie' && localPlusCookieStore._is_supported()) {
1440
+ store = localPlusCookieStore;
1441
+ } else if (storage_type === 'sessionstorage' && sessionStore._is_supported()) {
1442
+ store = sessionStore;
1443
+ } else if (storage_type === 'memory') {
1444
+ store = memoryStore;
1445
+ } else if (storage_type === 'cookie') {
1446
+ store = cookieStore;
1447
+ } else if (localPlusCookieStore._is_supported()) {
1448
+ store = localPlusCookieStore;
1449
+ } else {
1450
+ store = cookieStore;
1451
+ }
1452
+ return store;
1453
+ }
1454
+ properties() {
1455
+ const p = {};
1456
+ // Filter out reserved properties
1457
+ each(this.props, function (v, k) {
1458
+ if (k === ENABLED_FEATURE_FLAGS && core.isObject(v)) {
1459
+ const keys = Object.keys(v);
1460
+ for (let i = 0; i < keys.length; i++) {
1461
+ p[`$feature/${keys[i]}`] = v[keys[i]];
1462
+ }
1463
+ } else if (!include(PERSISTENCE_RESERVED_PROPERTIES, k)) {
1464
+ p[k] = v;
1465
+ }
1466
+ });
1467
+ return p;
1468
+ }
1469
+ load() {
1470
+ if (this._disabled) {
1471
+ return;
1472
+ }
1473
+ const entry = this._storage._parse(this._name);
1474
+ if (entry) {
1475
+ this.props = extend({}, entry);
1476
+ }
1477
+ }
1478
+ /**
1479
+ * NOTE: Saving frequently causes issues with Recordings and Consent Management Platform (CMP) tools which
1480
+ * observe cookie changes, and modify their UI, often causing infinite loops.
1481
+ * As such callers of this should ideally check that the data has changed beforehand
1482
+ */
1483
+ save() {
1484
+ if (this._disabled) {
1485
+ return;
1486
+ }
1487
+ this._storage._set(this._name, this.props, this._expire_days, this._cross_subdomain, this._secure, this._config.debug);
1488
+ }
1489
+ remove() {
1490
+ this._storage._remove(this._name, false);
1491
+ this._storage._remove(this._name, true);
1492
+ }
1493
+ clear() {
1494
+ this.remove();
1495
+ this.props = {};
1496
+ }
1497
+ /**
1498
+ * @param {Object} props
1499
+ * @param {*=} default_value
1500
+ * @param {number=} days
1501
+ */
1502
+ register_once(props, default_value, days) {
1503
+ if (core.isObject(props)) {
1504
+ if (core.isUndefined(default_value)) {
1505
+ default_value = 'None';
1506
+ }
1507
+ this._expire_days = core.isUndefined(days) ? this._default_expiry : days;
1508
+ let hasChanges = false;
1509
+ each(props, (val, prop) => {
1510
+ if (!this.props.hasOwnProperty(prop) || this.props[prop] === default_value) {
1511
+ this.props[prop] = val;
1512
+ hasChanges = true;
1513
+ }
1514
+ });
1515
+ if (hasChanges) {
1516
+ this.save();
1517
+ return true;
1518
+ }
1519
+ }
1520
+ return false;
1521
+ }
1522
+ /**
1523
+ * @param {Object} props
1524
+ * @param {number=} days
1525
+ */
1526
+ register(props, days) {
1527
+ if (core.isObject(props)) {
1528
+ this._expire_days = core.isUndefined(days) ? this._default_expiry : days;
1529
+ let hasChanges = false;
1530
+ each(props, (val, prop) => {
1531
+ if (props.hasOwnProperty(prop) && this.props[prop] !== val) {
1532
+ this.props[prop] = val;
1533
+ hasChanges = true;
1534
+ }
1535
+ });
1536
+ if (hasChanges) {
1537
+ this.save();
1538
+ return true;
1539
+ }
1540
+ }
1541
+ return false;
1542
+ }
1543
+ unregister(prop) {
1544
+ if (prop in this.props) {
1545
+ delete this.props[prop];
1546
+ this.save();
1547
+ }
1548
+ }
1549
+ update_campaign_params() {
1550
+ if (!this._campaign_params_saved) {
1551
+ const campaignParams = getCampaignParams(this._config.custom_campaign_params, this._config.mask_personal_data_properties, this._config.custom_personal_data_properties);
1552
+ if (!core.isEmptyObject(stripEmptyProperties(campaignParams))) {
1553
+ this.register(campaignParams);
1554
+ }
1555
+ this._campaign_params_saved = true;
1556
+ }
1557
+ }
1558
+ update_search_keyword() {
1559
+ this.register(getSearchInfo());
1560
+ }
1561
+ update_referrer_info() {
1562
+ this.register_once(getReferrerInfo(), undefined);
1563
+ }
1564
+ set_initial_person_info() {
1565
+ if (this.props[INITIAL_CAMPAIGN_PARAMS] || this.props[INITIAL_REFERRER_INFO]) {
1566
+ return;
1567
+ }
1568
+ this.register_once({
1569
+ [INITIAL_PERSON_INFO]: getPersonInfo(this._config.mask_personal_data_properties, this._config.custom_personal_data_properties)
1570
+ }, undefined);
1571
+ }
1572
+ get_initial_props() {
1573
+ const p = {};
1574
+ each([INITIAL_REFERRER_INFO, INITIAL_CAMPAIGN_PARAMS], key => {
1575
+ const initialReferrerInfo = this.props[key];
1576
+ if (initialReferrerInfo) {
1577
+ each(initialReferrerInfo, function (v, k) {
1578
+ p['$initial_' + core.stripLeadingDollar(k)] = v;
1579
+ });
1580
+ }
1581
+ });
1582
+ const initialPersonInfo = this.props[INITIAL_PERSON_INFO];
1583
+ if (initialPersonInfo) {
1584
+ const initialPersonProps = getInitialPersonPropsFromInfo(initialPersonInfo);
1585
+ extend(p, initialPersonProps);
1586
+ }
1587
+ return p;
1588
+ }
1589
+ safe_merge(props) {
1590
+ each(this.props, function (val, prop) {
1591
+ if (!(prop in props)) {
1592
+ props[prop] = val;
1593
+ }
1594
+ });
1595
+ return props;
1596
+ }
1597
+ update_config(config, oldConfig, isDisabled) {
1598
+ this._default_expiry = this._expire_days = config['cookie_expiration'];
1599
+ this.set_disabled(config['disable_persistence'] || !!isDisabled);
1600
+ this.set_cross_subdomain(config['cross_subdomain_cookie']);
1601
+ this.set_secure(config['secure_cookie']);
1602
+ if (config.persistence !== oldConfig.persistence) {
1603
+ const newStore = this._buildStorage(config);
1604
+ const props = this.props;
1605
+ this.clear();
1606
+ this._storage = newStore;
1607
+ this.props = props;
1608
+ this.save();
1609
+ }
1610
+ }
1611
+ set_disabled(disabled) {
1612
+ this._disabled = disabled;
1613
+ if (this._disabled) {
1614
+ return this.remove();
1615
+ }
1616
+ this.save();
1617
+ }
1618
+ set_cross_subdomain(cross_subdomain) {
1619
+ if (cross_subdomain !== this._cross_subdomain) {
1620
+ this._cross_subdomain = cross_subdomain;
1621
+ this.remove();
1622
+ this.save();
1623
+ }
1624
+ }
1625
+ set_secure(secure) {
1626
+ if (secure !== this._secure) {
1627
+ this._secure = secure;
1628
+ this.remove();
1629
+ this.save();
1630
+ }
1631
+ }
1632
+ set_event_timer(event_name, timestamp) {
1633
+ const timers = this.props[EVENT_TIMERS_KEY] || {};
1634
+ timers[event_name] = timestamp;
1635
+ this.props[EVENT_TIMERS_KEY] = timers;
1636
+ this.save();
1637
+ }
1638
+ remove_event_timer(event_name) {
1639
+ const timers = this.props[EVENT_TIMERS_KEY] || {};
1640
+ const timestamp = timers[event_name];
1641
+ if (!core.isUndefined(timestamp)) {
1642
+ delete this.props[EVENT_TIMERS_KEY][event_name];
1643
+ this.save();
1644
+ }
1645
+ return timestamp;
1646
+ }
1647
+ get_property(prop) {
1648
+ return this.props[prop];
1649
+ }
1650
+ set_property(prop, to) {
1651
+ this.props[prop] = to;
1652
+ this.save();
1653
+ }
1654
+ }
1655
+
1656
+ /*
1657
+ * Check whether an element has nodeType Node.ELEMENT_NODE
1658
+ * @param {Element} el - element to check
1659
+ * @returns {boolean} whether el is of the correct nodeType
1660
+ */
1661
+ function isElementNode(el) {
1662
+ return !!el && el.nodeType === 1; // Node.ELEMENT_NODE - use integer constant for browser portability
1663
+ }
1664
+ /*
1665
+ * Check whether an element is of a given tag type.
1666
+ * Due to potential reference discrepancies (such as the webcomponents.js polyfill),
1667
+ * we want to match tagNames instead of specific references because something like
1668
+ * element === document.body won't always work because element might not be a native
1669
+ * element.
1670
+ * @param {Element} el - element to check
1671
+ * @param {string} tag - tag name (e.g., "div")
1672
+ * @returns {boolean} whether el is of the given tag type
1673
+ */
1674
+ function isTag(el, tag) {
1675
+ return !!el && !!el.tagName && el.tagName.toLowerCase() === tag.toLowerCase();
1676
+ }
1677
+ /*
1678
+ * Check whether an element has nodeType Node.TEXT_NODE
1679
+ * @param {Element} el - element to check
1680
+ * @returns {boolean} whether el is of the correct nodeType
1681
+ */
1682
+ function isTextNode(el) {
1683
+ return !!el && el.nodeType === 3; // Node.TEXT_NODE - use integer constant for browser portability
1684
+ }
1685
+ /*
1686
+ * Check whether an element has nodeType Node.DOCUMENT_FRAGMENT_NODE
1687
+ * @param {Element} el - element to check
1688
+ * @returns {boolean} whether el is of the correct nodeType
1689
+ */
1690
+ function isDocumentFragment(el) {
1691
+ return !!el && el.nodeType === 11; // Node.DOCUMENT_FRAGMENT_NODE - use integer constant for browser portability
1692
+ }
1693
+
1694
+ function splitClassString(s) {
1695
+ return s ? core.trim(s).split(/\s+/) : [];
1696
+ }
1697
+ function checkForURLMatches(urlsList) {
1698
+ const url = window?.location.href;
1699
+ return !!(url && urlsList && urlsList.some(regex => url.match(regex)));
1700
+ }
1701
+ /*
1702
+ * Get the className of an element, accounting for edge cases where element.className is an object
1703
+ *
1704
+ * Because this is a string it can contain unexpected characters
1705
+ * So, this method safely splits the className and returns that array.
1706
+ */
1707
+ function getClassNames(el) {
1708
+ let className = '';
1709
+ switch (typeof el.className) {
1710
+ case 'string':
1711
+ className = el.className;
1712
+ break;
1713
+ // TODO: when is this ever used?
1714
+ case 'object':
1715
+ // handle cases where className might be SVGAnimatedString or some other type
1716
+ className = (el.className && 'baseVal' in el.className ? el.className.baseVal : null) || el.getAttribute('class') || '';
1717
+ break;
1718
+ default:
1719
+ className = '';
1720
+ }
1721
+ return splitClassString(className);
1722
+ }
1723
+ function makeSafeText(s) {
1724
+ if (core.isNullish(s)) {
1725
+ return null;
1726
+ }
1727
+ return core.trim(s)
1728
+ // scrub potentially sensitive values
1729
+ .split(/(\s+)/).filter(s => shouldCaptureValue(s)).join('')
1730
+ // normalize whitespace
1731
+ .replace(/[\r\n]/g, ' ').replace(/[ ]+/g, ' ')
1732
+ // truncate
1733
+ .substring(0, 255);
1734
+ }
1735
+ /*
1736
+ * Get the direct text content of an element, protecting against sensitive data collection.
1737
+ * Concats textContent of each of the element's text node children; this avoids potential
1738
+ * collection of sensitive data that could happen if we used element.textContent and the
1739
+ * element had sensitive child elements, since element.textContent includes child content.
1740
+ * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).
1741
+ * @param {Element} el - element to get the text of
1742
+ * @returns {string} the element's direct text content
1743
+ */
1744
+ function getSafeText(el) {
1745
+ let elText = '';
1746
+ if (shouldCaptureElement(el) && !isSensitiveElement(el) && el.childNodes && el.childNodes.length) {
1747
+ each(el.childNodes, function (child) {
1748
+ if (isTextNode(child) && child.textContent) {
1749
+ elText += makeSafeText(child.textContent) ?? '';
1750
+ }
1751
+ });
1752
+ }
1753
+ return core.trim(elText);
1754
+ }
1755
+ function getEventTarget(e) {
1756
+ // https://developer.mozilla.org/en-US/docs/Web/API/Event/target#Compatibility_notes
1757
+ if (core.isUndefined(e.target)) {
1758
+ return e.srcElement || null;
1759
+ } else {
1760
+ if (e.target?.shadowRoot) {
1761
+ return e.composedPath()[0] || null;
1762
+ }
1763
+ return e.target || null;
1764
+ }
1765
+ }
1766
+ const autocaptureCompatibleElements = ['a', 'button', 'form', 'input', 'select', 'textarea', 'label'];
1767
+ /*
1768
+ if there is no config, then all elements are allowed
1769
+ if there is a config, and there is an allow list, then only elements in the allow list are allowed
1770
+ assumes that some other code is checking this element's parents
1771
+ */
1772
+ function checkIfElementTreePassesElementAllowList(elements, autocaptureConfig) {
1773
+ const allowlist = autocaptureConfig?.element_allowlist;
1774
+ if (core.isUndefined(allowlist)) {
1775
+ // everything is allowed, when there is no allow list
1776
+ return true;
1777
+ }
1778
+ // check each element in the tree
1779
+ // if any of the elements are in the allow list, then the tree is allowed
1780
+ for (const el of elements) {
1781
+ if (allowlist.some(elementType => el.tagName.toLowerCase() === elementType)) {
1782
+ return true;
20
1783
  }
21
- },
22
- error: (...args) => {
23
- if (typeof console !== 'undefined') {
24
- // eslint-disable-next-line no-console
25
- console.error(PREFIX, ...args);
1784
+ }
1785
+ // otherwise there is an allow list and this element tree didn't match it
1786
+ return false;
1787
+ }
1788
+ /*
1789
+ if there is no selector list (i.e. it is undefined), then any elements matches
1790
+ if there is an empty list, then no elements match
1791
+ if there is a selector list, then check it against each element provided
1792
+ */
1793
+ function checkIfElementsMatchCSSSelector(elements, selectorList) {
1794
+ if (core.isUndefined(selectorList)) {
1795
+ // everything is allowed, when there is no selector list
1796
+ return true;
1797
+ }
1798
+ for (const el of elements) {
1799
+ if (selectorList.some(selector => el.matches(selector))) {
1800
+ return true;
1801
+ }
1802
+ }
1803
+ return false;
1804
+ }
1805
+ function getParentElement(curEl) {
1806
+ const parentNode = curEl.parentNode;
1807
+ if (!parentNode || !isElementNode(parentNode)) return false;
1808
+ return parentNode;
1809
+ }
1810
+ // autocapture check will already filter for ph-no-capture,
1811
+ // but we include it here to protect against future changes accidentally removing that check
1812
+ const DEFAULT_RAGE_CLICK_IGNORE_LIST = ['.ph-no-rageclick', '.ph-no-capture'];
1813
+ function shouldCaptureRageclick(el, _config) {
1814
+ if (!window || cannotCheckForAutocapture(el)) {
1815
+ return false;
1816
+ }
1817
+ let selectorIgnoreList;
1818
+ if (core.isBoolean(_config)) {
1819
+ selectorIgnoreList = _config ? DEFAULT_RAGE_CLICK_IGNORE_LIST : false;
1820
+ } else {
1821
+ selectorIgnoreList = _config?.css_selector_ignorelist ?? DEFAULT_RAGE_CLICK_IGNORE_LIST;
1822
+ }
1823
+ if (selectorIgnoreList === false) {
1824
+ return false;
1825
+ }
1826
+ const {
1827
+ targetElementList
1828
+ } = getElementAndParentsForElement(el, false);
1829
+ // we don't capture if we match the ignore list
1830
+ return !checkIfElementsMatchCSSSelector(targetElementList, selectorIgnoreList);
1831
+ }
1832
+ const cannotCheckForAutocapture = el => {
1833
+ return !el || isTag(el, 'html') || !isElementNode(el);
1834
+ };
1835
+ const getElementAndParentsForElement = (el, captureOnAnyElement) => {
1836
+ if (!window || cannotCheckForAutocapture(el)) {
1837
+ return {
1838
+ parentIsUsefulElement: false,
1839
+ targetElementList: []
1840
+ };
1841
+ }
1842
+ let parentIsUsefulElement = false;
1843
+ const targetElementList = [el];
1844
+ let curEl = el;
1845
+ while (curEl.parentNode && !isTag(curEl, 'body')) {
1846
+ // If element is a shadow root, we skip it
1847
+ if (isDocumentFragment(curEl.parentNode)) {
1848
+ targetElementList.push(curEl.parentNode.host);
1849
+ curEl = curEl.parentNode.host;
1850
+ continue;
1851
+ }
1852
+ const parentNode = getParentElement(curEl);
1853
+ if (!parentNode) break;
1854
+ if (captureOnAnyElement || autocaptureCompatibleElements.indexOf(parentNode.tagName.toLowerCase()) > -1) {
1855
+ parentIsUsefulElement = true;
1856
+ } else {
1857
+ const compStyles = window.getComputedStyle(parentNode);
1858
+ if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer') {
1859
+ parentIsUsefulElement = true;
1860
+ }
26
1861
  }
1862
+ targetElementList.push(parentNode);
1863
+ curEl = parentNode;
27
1864
  }
1865
+ return {
1866
+ parentIsUsefulElement,
1867
+ targetElementList
1868
+ };
28
1869
  };
1870
+ /*
1871
+ * Check whether a DOM event should be "captured" or if it may contain sensitive data
1872
+ * using a variety of heuristics.
1873
+ * @param {Element} el - element to check
1874
+ * @param {Event} event - event to check
1875
+ * @param {Object} autocaptureConfig - autocapture config
1876
+ * @param {boolean} captureOnAnyElement - whether to capture on any element, clipboard autocapture doesn't restrict to "clickable" elements
1877
+ * @param {string[]} allowedEventTypes - event types to capture, normally just 'click', but some autocapture types react to different events, some elements have fixed events (e.g., form has "submit")
1878
+ * @returns {boolean} whether the event should be captured
1879
+ */
1880
+ function shouldCaptureDomEvent(el, event, autocaptureConfig = undefined, captureOnAnyElement, allowedEventTypes) {
1881
+ if (!window || cannotCheckForAutocapture(el)) {
1882
+ return false;
1883
+ }
1884
+ if (autocaptureConfig?.url_allowlist) {
1885
+ // if the current URL is not in the allow list, don't capture
1886
+ if (!checkForURLMatches(autocaptureConfig.url_allowlist)) {
1887
+ return false;
1888
+ }
1889
+ }
1890
+ if (autocaptureConfig?.url_ignorelist) {
1891
+ // if the current URL is in the ignore list, don't capture
1892
+ if (checkForURLMatches(autocaptureConfig.url_ignorelist)) {
1893
+ return false;
1894
+ }
1895
+ }
1896
+ if (autocaptureConfig?.dom_event_allowlist) {
1897
+ const allowlist = autocaptureConfig.dom_event_allowlist;
1898
+ if (allowlist && !allowlist.some(eventType => event.type === eventType)) {
1899
+ return false;
1900
+ }
1901
+ }
1902
+ const {
1903
+ parentIsUsefulElement,
1904
+ targetElementList
1905
+ } = getElementAndParentsForElement(el, captureOnAnyElement);
1906
+ if (!checkIfElementTreePassesElementAllowList(targetElementList, autocaptureConfig)) {
1907
+ return false;
1908
+ }
1909
+ if (!checkIfElementsMatchCSSSelector(targetElementList, autocaptureConfig?.css_selector_allowlist)) {
1910
+ return false;
1911
+ }
1912
+ const compStyles = window.getComputedStyle(el);
1913
+ if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer' && event.type === 'click') {
1914
+ return true;
1915
+ }
1916
+ const tag = el.tagName.toLowerCase();
1917
+ switch (tag) {
1918
+ case 'html':
1919
+ return false;
1920
+ case 'form':
1921
+ return (allowedEventTypes || ['submit']).indexOf(event.type) >= 0;
1922
+ case 'input':
1923
+ case 'select':
1924
+ case 'textarea':
1925
+ return (allowedEventTypes || ['change', 'click']).indexOf(event.type) >= 0;
1926
+ default:
1927
+ if (parentIsUsefulElement) return (allowedEventTypes || ['click']).indexOf(event.type) >= 0;
1928
+ return (allowedEventTypes || ['click']).indexOf(event.type) >= 0 && (autocaptureCompatibleElements.indexOf(tag) > -1 || el.getAttribute('contenteditable') === 'true');
1929
+ }
1930
+ }
1931
+ /*
1932
+ * Check whether a DOM element should be "captured" or if it may contain sensitive data
1933
+ * using a variety of heuristics.
1934
+ * @param {Element} el - element to check
1935
+ * @returns {boolean} whether the element should be captured
1936
+ */
1937
+ function shouldCaptureElement(el) {
1938
+ for (let curEl = el; curEl.parentNode && !isTag(curEl, 'body'); curEl = curEl.parentNode) {
1939
+ const classes = getClassNames(curEl);
1940
+ if (core.includes(classes, 'ph-sensitive') || core.includes(classes, 'ph-no-capture')) {
1941
+ return false;
1942
+ }
1943
+ }
1944
+ if (core.includes(getClassNames(el), 'ph-include')) {
1945
+ return true;
1946
+ }
1947
+ // don't include hidden or password fields
1948
+ const type = el.type || '';
1949
+ if (core.isString(type)) {
1950
+ // it's possible for el.type to be a DOM element if el is a form with a child input[name="type"]
1951
+ switch (type.toLowerCase()) {
1952
+ case 'hidden':
1953
+ return false;
1954
+ case 'password':
1955
+ return false;
1956
+ }
1957
+ }
1958
+ // filter out data from fields that look like sensitive fields
1959
+ const name = el.name || el.id || '';
1960
+ // See https://github.com/posthog/posthog-js/issues/165
1961
+ // Under specific circumstances a bug caused .replace to be called on a DOM element
1962
+ // instead of a string, removing the element from the page. Ensure this issue is mitigated.
1963
+ if (core.isString(name)) {
1964
+ // 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"]
1965
+ const sensitiveNameRegex = /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i;
1966
+ if (sensitiveNameRegex.test(name.replace(/[^a-zA-Z0-9]/g, ''))) {
1967
+ return false;
1968
+ }
1969
+ }
1970
+ return true;
1971
+ }
1972
+ /*
1973
+ * Check whether a DOM element is 'sensitive' and we should only capture limited data
1974
+ * @param {Element} el - element to check
1975
+ * @returns {boolean} whether the element should be captured
1976
+ */
1977
+ function isSensitiveElement(el) {
1978
+ // don't send data from inputs or similar elements since there will always be
1979
+ // a risk of clientside javascript placing sensitive data in attributes
1980
+ const allowedInputTypes = ['button', 'checkbox', 'submit', 'reset'];
1981
+ if (isTag(el, 'input') && !allowedInputTypes.includes(el.type) || isTag(el, 'select') || isTag(el, 'textarea') || el.getAttribute('contenteditable') === 'true') {
1982
+ return true;
1983
+ }
1984
+ return false;
1985
+ }
1986
+ // Define the core pattern for matching credit card numbers
1987
+ const coreCCPattern = `(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})`;
1988
+ // Create the Anchored version of the regex by adding '^' at the start and '$' at the end
1989
+ const anchoredCCRegex = new RegExp(`^(?:${coreCCPattern})$`);
1990
+ // The Unanchored version is essentially the core pattern, usable as is for partial matches
1991
+ const unanchoredCCRegex = new RegExp(coreCCPattern);
1992
+ // Define the core pattern for matching SSNs with optional dashes
1993
+ const coreSSNPattern = `\\d{3}-?\\d{2}-?\\d{4}`;
1994
+ // Create the Anchored version of the regex by adding '^' at the start and '$' at the end
1995
+ const anchoredSSNRegex = new RegExp(`^(${coreSSNPattern})$`);
1996
+ // The Unanchored version is essentially the core pattern itself, usable for partial matches
1997
+ const unanchoredSSNRegex = new RegExp(`(${coreSSNPattern})`);
1998
+ /*
1999
+ * Check whether a string value should be "captured" or if it may contain sensitive data
2000
+ * using a variety of heuristics.
2001
+ * @param {string} value - string value to check
2002
+ * @param {boolean} anchorRegexes - whether to anchor the regexes to the start and end of the string
2003
+ * @returns {boolean} whether the element should be captured
2004
+ */
2005
+ function shouldCaptureValue(value, anchorRegexes = true) {
2006
+ if (core.isNullish(value)) {
2007
+ return false;
2008
+ }
2009
+ if (core.isString(value)) {
2010
+ value = core.trim(value);
2011
+ // check to see if input value looks like a credit card number
2012
+ // see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html
2013
+ const ccRegex = anchorRegexes ? anchoredCCRegex : unanchoredCCRegex;
2014
+ if (ccRegex.test((value || '').replace(/[- ]/g, ''))) {
2015
+ return false;
2016
+ }
2017
+ // check to see if input value looks like a social security number
2018
+ const ssnRegex = anchorRegexes ? anchoredSSNRegex : unanchoredSSNRegex;
2019
+ if (ssnRegex.test(value)) {
2020
+ return false;
2021
+ }
2022
+ }
2023
+ return true;
2024
+ }
2025
+ /*
2026
+ * Check whether an attribute name is an Angular style attr (either _ngcontent or _nghost)
2027
+ * These update on each build and lead to noise in the element chain
2028
+ * More details on the attributes here: https://angular.io/guide/view-encapsulation
2029
+ * @param {string} attributeName - string value to check
2030
+ * @returns {boolean} whether the element is an angular tag
2031
+ */
2032
+ function isAngularStyleAttr(attributeName) {
2033
+ if (core.isString(attributeName)) {
2034
+ return attributeName.substring(0, 10) === '_ngcontent' || attributeName.substring(0, 7) === '_nghost';
2035
+ }
2036
+ return false;
2037
+ }
2038
+ /*
2039
+ * Iterate through children of a target element looking for span tags
2040
+ * and return the text content of the span tags, separated by spaces,
2041
+ * along with the direct text content of the target element
2042
+ * @param {Element} target - element to check
2043
+ * @returns {string} text content of the target element and its child span tags
2044
+ */
2045
+ function getDirectAndNestedSpanText(target) {
2046
+ let text = getSafeText(target);
2047
+ text = `${text} ${getNestedSpanText(target)}`.trim();
2048
+ return shouldCaptureValue(text) ? text : '';
2049
+ }
2050
+ /*
2051
+ * Iterate through children of a target element looking for span tags
2052
+ * and return the text content of the span tags, separated by spaces
2053
+ * @param {Element} target - element to check
2054
+ * @returns {string} text content of span tags
2055
+ */
2056
+ function getNestedSpanText(target) {
2057
+ let text = '';
2058
+ if (target && target.childNodes && target.childNodes.length) {
2059
+ each(target.childNodes, function (child) {
2060
+ if (child && child.tagName?.toLowerCase() === 'span') {
2061
+ try {
2062
+ const spanText = getSafeText(child);
2063
+ text = `${text} ${spanText}`.trim();
2064
+ if (child.childNodes && child.childNodes.length) {
2065
+ text = `${text} ${getNestedSpanText(child)}`.trim();
2066
+ }
2067
+ } catch (e) {
2068
+ logger.error('[AutoCapture]', e);
2069
+ }
2070
+ }
2071
+ });
2072
+ }
2073
+ return text;
2074
+ }
2075
+ /*
2076
+ Back in the day storing events in Postgres we use Elements for autocapture events.
2077
+ Now we're using elements_chain. We used to do this parsing/processing during ingestion.
2078
+ This code is just copied over from ingestion, but we should optimize it
2079
+ to create elements_chain string directly.
2080
+ */
2081
+ function getElementsChainString(elements) {
2082
+ return elementsToString(extractElements(elements));
2083
+ }
2084
+ function escapeQuotes(input) {
2085
+ return input.replace(/"|\\"/g, '\\"');
2086
+ }
2087
+ function elementsToString(elements) {
2088
+ const ret = elements.map(element => {
2089
+ let el_string = '';
2090
+ if (element.tag_name) {
2091
+ el_string += element.tag_name;
2092
+ }
2093
+ if (element.attr_class) {
2094
+ element.attr_class.sort();
2095
+ for (const single_class of element.attr_class) {
2096
+ el_string += `.${single_class.replace(/"/g, '')}`;
2097
+ }
2098
+ }
2099
+ const attributes = {
2100
+ ...(element.text ? {
2101
+ text: element.text
2102
+ } : {}),
2103
+ 'nth-child': element.nth_child ?? 0,
2104
+ 'nth-of-type': element.nth_of_type ?? 0,
2105
+ ...(element.href ? {
2106
+ href: element.href
2107
+ } : {}),
2108
+ ...(element.attr_id ? {
2109
+ attr_id: element.attr_id
2110
+ } : {}),
2111
+ ...element.attributes
2112
+ };
2113
+ const sortedAttributes = {};
2114
+ entries(attributes).sort(([a], [b]) => a.localeCompare(b)).forEach(([key, value]) => sortedAttributes[escapeQuotes(key.toString())] = escapeQuotes(value.toString()));
2115
+ el_string += ':';
2116
+ el_string += entries(sortedAttributes).map(([key, value]) => `${key}="${value}"`).join('');
2117
+ return el_string;
2118
+ });
2119
+ return ret.join(';');
2120
+ }
2121
+ function extractElements(elements) {
2122
+ return elements.map(el => {
2123
+ const response = {
2124
+ text: el['$el_text']?.slice(0, 400),
2125
+ tag_name: el['tag_name'],
2126
+ href: el['attr__href']?.slice(0, 2048),
2127
+ attr_class: extractAttrClass(el),
2128
+ attr_id: el['attr__id'],
2129
+ nth_child: el['nth_child'],
2130
+ nth_of_type: el['nth_of_type'],
2131
+ attributes: {}
2132
+ };
2133
+ entries(el).filter(([key]) => key.indexOf('attr__') === 0).forEach(([key, value]) => response.attributes[key] = value);
2134
+ return response;
2135
+ });
2136
+ }
2137
+ function extractAttrClass(el) {
2138
+ const attr_class = el['attr__class'];
2139
+ if (!attr_class) {
2140
+ return undefined;
2141
+ } else if (core.isArray(attr_class)) {
2142
+ return attr_class;
2143
+ } else {
2144
+ return splitClassString(attr_class);
2145
+ }
2146
+ }
29
2147
 
30
- class Leanbase extends core.PostHogCore {
31
- constructor(apiKey, options) {
32
- // Leanbase defaults
33
- const leanbaseOptions = {
34
- host: 'https://i.leanbase.co',
35
- ...options
2148
+ // Naive rage click implementation: If mouse has not moved further than RAGE_CLICK_THRESHOLD_PX
2149
+ // over RAGE_CLICK_CLICK_COUNT clicks with max RAGE_CLICK_TIMEOUT_MS between clicks, it's
2150
+ // counted as a rage click
2151
+ const RAGE_CLICK_THRESHOLD_PX = 30;
2152
+ const RAGE_CLICK_TIMEOUT_MS = 1000;
2153
+ const RAGE_CLICK_CLICK_COUNT = 3;
2154
+ class RageClick {
2155
+ constructor() {
2156
+ this.clicks = [];
2157
+ }
2158
+ isRageClick(x, y, timestamp) {
2159
+ const lastClick = this.clicks[this.clicks.length - 1];
2160
+ if (lastClick && Math.abs(x - lastClick.x) + Math.abs(y - lastClick.y) < RAGE_CLICK_THRESHOLD_PX && timestamp - lastClick.timestamp < RAGE_CLICK_TIMEOUT_MS) {
2161
+ this.clicks.push({
2162
+ x,
2163
+ y,
2164
+ timestamp
2165
+ });
2166
+ if (this.clicks.length === RAGE_CLICK_CLICK_COUNT) {
2167
+ return true;
2168
+ }
2169
+ } else {
2170
+ this.clicks = [{
2171
+ x,
2172
+ y,
2173
+ timestamp
2174
+ }];
2175
+ }
2176
+ return false;
2177
+ }
2178
+ }
2179
+
2180
+ const COPY_AUTOCAPTURE_EVENT = '$copy_autocapture';
2181
+ var Compression;
2182
+ (function (Compression) {
2183
+ Compression["GZipJS"] = "gzip-js";
2184
+ Compression["Base64"] = "base64";
2185
+ })(Compression || (Compression = {}));
2186
+
2187
+ function limitText(length, text) {
2188
+ if (text.length > length) {
2189
+ return text.slice(0, length) + '...';
2190
+ }
2191
+ return text;
2192
+ }
2193
+ function getAugmentPropertiesFromElement(elem) {
2194
+ const shouldCaptureEl = shouldCaptureElement(elem);
2195
+ if (!shouldCaptureEl) {
2196
+ return {};
2197
+ }
2198
+ const props = {};
2199
+ each(elem.attributes, function (attr) {
2200
+ if (attr.name && attr.name.indexOf('data-ph-capture-attribute') === 0) {
2201
+ const propertyKey = attr.name.replace('data-ph-capture-attribute-', '');
2202
+ const propertyValue = attr.value;
2203
+ if (propertyKey && propertyValue && shouldCaptureValue(propertyValue)) {
2204
+ props[propertyKey] = propertyValue;
2205
+ }
2206
+ }
2207
+ });
2208
+ return props;
2209
+ }
2210
+ function previousElementSibling(el) {
2211
+ if (el.previousElementSibling) {
2212
+ return el.previousElementSibling;
2213
+ }
2214
+ let _el = el;
2215
+ do {
2216
+ _el = _el.previousSibling; // resolves to ChildNode->Node, which is Element's parent class
2217
+ } while (_el && !isElementNode(_el));
2218
+ return _el;
2219
+ }
2220
+ function getDefaultProperties(eventType) {
2221
+ return {
2222
+ $event_type: eventType,
2223
+ $ce_version: 1
2224
+ };
2225
+ }
2226
+ function getPropertiesFromElement(elem, maskAllAttributes, maskText, elementAttributeIgnorelist) {
2227
+ const tag_name = elem.tagName.toLowerCase();
2228
+ const props = {
2229
+ tag_name: tag_name
2230
+ };
2231
+ if (autocaptureCompatibleElements.indexOf(tag_name) > -1 && !maskText) {
2232
+ if (tag_name.toLowerCase() === 'a' || tag_name.toLowerCase() === 'button') {
2233
+ props['$el_text'] = limitText(1024, getDirectAndNestedSpanText(elem));
2234
+ } else {
2235
+ props['$el_text'] = limitText(1024, getSafeText(elem));
2236
+ }
2237
+ }
2238
+ const classes = getClassNames(elem);
2239
+ if (classes.length > 0) props['classes'] = classes.filter(function (c) {
2240
+ return c !== '';
2241
+ });
2242
+ // capture the deny list here because this not-a-class class makes it tricky to use this.config in the function below
2243
+ each(elem.attributes, function (attr) {
2244
+ // Only capture attributes we know are safe
2245
+ if (isSensitiveElement(elem) && ['name', 'id', 'class', 'aria-label'].indexOf(attr.name) === -1) return;
2246
+ if (elementAttributeIgnorelist?.includes(attr.name)) return;
2247
+ if (!maskAllAttributes && shouldCaptureValue(attr.value) && !isAngularStyleAttr(attr.name)) {
2248
+ let value = attr.value;
2249
+ if (attr.name === 'class') {
2250
+ // html attributes can _technically_ contain linebreaks,
2251
+ // but we're very intolerant of them in the class string,
2252
+ // so we strip them.
2253
+ value = splitClassString(value).join(' ');
2254
+ }
2255
+ props['attr__' + attr.name] = limitText(1024, value);
2256
+ }
2257
+ });
2258
+ let nthChild = 1;
2259
+ let nthOfType = 1;
2260
+ let currentElem = elem;
2261
+ while (currentElem = previousElementSibling(currentElem)) {
2262
+ // eslint-disable-line no-cond-assign
2263
+ nthChild++;
2264
+ if (currentElem.tagName === elem.tagName) {
2265
+ nthOfType++;
2266
+ }
2267
+ }
2268
+ props['nth_child'] = nthChild;
2269
+ props['nth_of_type'] = nthOfType;
2270
+ return props;
2271
+ }
2272
+ function autocapturePropertiesForElement(target, {
2273
+ e,
2274
+ maskAllElementAttributes,
2275
+ maskAllText,
2276
+ elementAttributeIgnoreList,
2277
+ elementsChainAsString
2278
+ }) {
2279
+ const targetElementList = [target];
2280
+ let curEl = target;
2281
+ while (curEl.parentNode && !isTag(curEl, 'body')) {
2282
+ if (isDocumentFragment(curEl.parentNode)) {
2283
+ targetElementList.push(curEl.parentNode.host);
2284
+ curEl = curEl.parentNode.host;
2285
+ continue;
2286
+ }
2287
+ targetElementList.push(curEl.parentNode);
2288
+ curEl = curEl.parentNode;
2289
+ }
2290
+ const elementsJson = [];
2291
+ const autocaptureAugmentProperties = {};
2292
+ let href = false;
2293
+ let explicitNoCapture = false;
2294
+ each(targetElementList, el => {
2295
+ const shouldCaptureEl = shouldCaptureElement(el);
2296
+ // if the element or a parent element is an anchor tag
2297
+ // include the href as a property
2298
+ if (el.tagName.toLowerCase() === 'a') {
2299
+ href = el.getAttribute('href');
2300
+ href = shouldCaptureEl && href && shouldCaptureValue(href) && href;
2301
+ }
2302
+ // allow users to programmatically prevent capturing of elements by adding class 'ph-no-capture'
2303
+ const classes = getClassNames(el);
2304
+ if (core.includes(classes, 'ph-no-capture')) {
2305
+ explicitNoCapture = true;
2306
+ }
2307
+ elementsJson.push(getPropertiesFromElement(el, maskAllElementAttributes, maskAllText, elementAttributeIgnoreList));
2308
+ const augmentProperties = getAugmentPropertiesFromElement(el);
2309
+ extend(autocaptureAugmentProperties, augmentProperties);
2310
+ });
2311
+ if (explicitNoCapture) {
2312
+ return {
2313
+ props: {},
2314
+ explicitNoCapture
36
2315
  };
37
- super(apiKey, leanbaseOptions);
38
- this._storage = new Map();
39
- this._storageKey = `leanbase_${apiKey}`;
40
- // Load from localStorage if available
41
- if (typeof window !== 'undefined' && window.localStorage) {
2316
+ }
2317
+ if (!maskAllText) {
2318
+ // if the element is a button or anchor tag get the span text from any
2319
+ // children and include it as/with the text property on the parent element
2320
+ if (target.tagName.toLowerCase() === 'a' || target.tagName.toLowerCase() === 'button') {
2321
+ elementsJson[0]['$el_text'] = getDirectAndNestedSpanText(target);
2322
+ } else {
2323
+ elementsJson[0]['$el_text'] = getSafeText(target);
2324
+ }
2325
+ }
2326
+ let externalHref;
2327
+ if (href) {
2328
+ elementsJson[0]['attr__href'] = href;
2329
+ const hrefHost = convertToURL(href)?.host;
2330
+ const locationHost = win?.location?.host;
2331
+ if (hrefHost && locationHost && hrefHost !== locationHost) {
2332
+ externalHref = href;
2333
+ }
2334
+ }
2335
+ const props = extend(getDefaultProperties(e.type),
2336
+ // Sending "$elements" is deprecated. Only one client on US cloud uses this.
2337
+ !elementsChainAsString ? {
2338
+ $elements: elementsJson
2339
+ } : {},
2340
+ // Always send $elements_chain, as it's needed downstream in site app filtering
2341
+ {
2342
+ $elements_chain: getElementsChainString(elementsJson)
2343
+ }, elementsJson[0]?.['$el_text'] ? {
2344
+ $el_text: elementsJson[0]?.['$el_text']
2345
+ } : {}, externalHref && e.type === 'click' ? {
2346
+ $external_click_url: externalHref
2347
+ } : {}, autocaptureAugmentProperties);
2348
+ return {
2349
+ props
2350
+ };
2351
+ }
2352
+ class Autocapture {
2353
+ constructor(instance) {
2354
+ this._initialized = false;
2355
+ this._isDisabledServerSide = null;
2356
+ this.rageclicks = new RageClick();
2357
+ this._elementsChainAsString = false;
2358
+ this.instance = instance;
2359
+ this._elementSelectors = null;
2360
+ }
2361
+ get _config() {
2362
+ const config = core.isObject(this.instance.config.autocapture) ? this.instance.config.autocapture : {};
2363
+ // precompile the regex
2364
+ config.url_allowlist = config.url_allowlist?.map(url => new RegExp(url));
2365
+ config.url_ignorelist = config.url_ignorelist?.map(url => new RegExp(url));
2366
+ return config;
2367
+ }
2368
+ _addDomEventHandlers() {
2369
+ if (!this.isBrowserSupported()) {
2370
+ logger.info('Disabling Automatic Event Collection because this browser is not supported');
2371
+ return;
2372
+ }
2373
+ if (!win || !document) {
2374
+ return;
2375
+ }
2376
+ const handler = e => {
2377
+ e = e || win?.event;
42
2378
  try {
43
- const stored = window.localStorage.getItem(this._storageKey);
44
- if (stored) {
45
- const parsed = JSON.parse(stored);
46
- Object.entries(parsed).forEach(([key, value]) => {
47
- this._storage.set(key, value);
48
- });
2379
+ this._captureEvent(e);
2380
+ } catch (error) {
2381
+ logger.error('Failed to capture event', error);
2382
+ }
2383
+ };
2384
+ addEventListener(document, 'submit', handler, {
2385
+ capture: true
2386
+ });
2387
+ addEventListener(document, 'change', handler, {
2388
+ capture: true
2389
+ });
2390
+ addEventListener(document, 'click', handler, {
2391
+ capture: true
2392
+ });
2393
+ if (this._config.capture_copied_text) {
2394
+ const copiedTextHandler = e => {
2395
+ e = e || win?.event;
2396
+ this._captureEvent(e, COPY_AUTOCAPTURE_EVENT);
2397
+ };
2398
+ addEventListener(document, 'copy', copiedTextHandler, {
2399
+ capture: true
2400
+ });
2401
+ addEventListener(document, 'cut', copiedTextHandler, {
2402
+ capture: true
2403
+ });
2404
+ }
2405
+ }
2406
+ startIfEnabled() {
2407
+ if (this.isEnabled && !this._initialized) {
2408
+ this._addDomEventHandlers();
2409
+ this._initialized = true;
2410
+ }
2411
+ }
2412
+ onRemoteConfig(response) {
2413
+ if (response.elementsChainAsString) {
2414
+ this._elementsChainAsString = response.elementsChainAsString;
2415
+ }
2416
+ if (this.instance.persistence) {
2417
+ this.instance.persistence.register({
2418
+ [AUTOCAPTURE_DISABLED_SERVER_SIDE]: !!response['autocapture_opt_out']
2419
+ });
2420
+ }
2421
+ this._isDisabledServerSide = !!response['autocapture_opt_out'];
2422
+ this.startIfEnabled();
2423
+ }
2424
+ setElementSelectors(selectors) {
2425
+ this._elementSelectors = selectors;
2426
+ }
2427
+ getElementSelectors(element) {
2428
+ const elementSelectors = [];
2429
+ this._elementSelectors?.forEach(selector => {
2430
+ const matchedElements = document?.querySelectorAll(selector);
2431
+ matchedElements?.forEach(matchedElement => {
2432
+ if (element === matchedElement) {
2433
+ elementSelectors.push(selector);
2434
+ }
2435
+ });
2436
+ });
2437
+ return elementSelectors;
2438
+ }
2439
+ get isEnabled() {
2440
+ const persistedServerDisabled = this.instance.persistence?.props[AUTOCAPTURE_DISABLED_SERVER_SIDE];
2441
+ const memoryDisabled = this._isDisabledServerSide;
2442
+ if (core.isNull(memoryDisabled) && !core.isBoolean(persistedServerDisabled)) {
2443
+ return false;
2444
+ }
2445
+ const disabledServer = this._isDisabledServerSide ?? !!persistedServerDisabled;
2446
+ const disabledClient = !this.instance.config.autocapture;
2447
+ return !disabledClient && !disabledServer;
2448
+ }
2449
+ _captureEvent(e, eventName = '$autocapture') {
2450
+ if (!this.isEnabled) {
2451
+ return;
2452
+ }
2453
+ /*** Don't mess with this code without running IE8 tests on it ***/
2454
+ let target = getEventTarget(e);
2455
+ if (isTextNode(target)) {
2456
+ // defeat Safari bug (see: http://www.quirksmode.org/js/events_properties.html)
2457
+ target = target.parentNode || null;
2458
+ }
2459
+ if (eventName === '$autocapture' && e.type === 'click' && e instanceof MouseEvent) {
2460
+ if (!!this.instance.config.rageclick && this.rageclicks?.isRageClick(e.clientX, e.clientY, new Date().getTime())) {
2461
+ if (shouldCaptureRageclick(target, this.instance.config.rageclick)) {
2462
+ this._captureEvent(e, '$rageclick');
2463
+ }
2464
+ }
2465
+ }
2466
+ const isCopyAutocapture = eventName === COPY_AUTOCAPTURE_EVENT;
2467
+ if (target && shouldCaptureDomEvent(target, e, this._config,
2468
+ // mostly this method cares about the target element, but in the case of copy events,
2469
+ // we want some of the work this check does without insisting on the target element's type
2470
+ isCopyAutocapture,
2471
+ // we also don't want to restrict copy checks to clicks,
2472
+ // so we pass that knowledge in here, rather than add the logic inside the check
2473
+ isCopyAutocapture ? ['copy', 'cut'] : undefined)) {
2474
+ const {
2475
+ props,
2476
+ explicitNoCapture
2477
+ } = autocapturePropertiesForElement(target, {
2478
+ e,
2479
+ maskAllElementAttributes: this.instance.config.mask_all_element_attributes,
2480
+ maskAllText: this.instance.config.mask_all_text,
2481
+ elementAttributeIgnoreList: this._config.element_attribute_ignorelist,
2482
+ elementsChainAsString: this._elementsChainAsString
2483
+ });
2484
+ if (explicitNoCapture) {
2485
+ return false;
2486
+ }
2487
+ const elementSelectors = this.getElementSelectors(target);
2488
+ if (elementSelectors && elementSelectors.length > 0) {
2489
+ props['$element_selectors'] = elementSelectors;
2490
+ }
2491
+ if (eventName === COPY_AUTOCAPTURE_EVENT) {
2492
+ // you can't read the data from the clipboard event,
2493
+ // but you can guess that you can read it from the window's current selection
2494
+ const selectedContent = makeSafeText(win?.getSelection()?.toString());
2495
+ const clipType = e.type || 'clipboard';
2496
+ if (!selectedContent) {
2497
+ return false;
2498
+ }
2499
+ props['$selected_content'] = selectedContent;
2500
+ props['$copy_type'] = clipType;
2501
+ }
2502
+ this.instance.capture(eventName, props);
2503
+ return true;
2504
+ }
2505
+ }
2506
+ isBrowserSupported() {
2507
+ return core.isFunction(document?.querySelectorAll);
2508
+ }
2509
+ }
2510
+
2511
+ // This keeps track of the PageView state (such as the previous PageView's path, timestamp, id, and scroll properties).
2512
+ // We store the state in memory, which means that for non-SPA sites, the state will be lost on page reload. This means
2513
+ // that non-SPA sites should always send a $pageleave event on any navigation, before the page unloads. For SPA sites,
2514
+ // they only need to send a $pageleave event when the user navigates away from the site, as the information is not lost
2515
+ // on an internal navigation, and is included as the $prev_pageview_ properties in the next $pageview event.
2516
+ // Practically, this means that to find the scroll properties for a given pageview, you need to find the event where
2517
+ // event name is $pageview or $pageleave and where $prev_pageview_id matches the original pageview event's id.
2518
+ class PageViewManager {
2519
+ constructor(instance) {
2520
+ this._instance = instance;
2521
+ }
2522
+ doPageView(timestamp, pageViewId) {
2523
+ const response = this._previousPageViewProperties(timestamp, pageViewId);
2524
+ // On a pageview we reset the contexts
2525
+ this._currentPageview = {
2526
+ pathname: win?.location.pathname ?? '',
2527
+ pageViewId,
2528
+ timestamp
2529
+ };
2530
+ this._instance.scrollManager.resetContext();
2531
+ return response;
2532
+ }
2533
+ doPageLeave(timestamp) {
2534
+ return this._previousPageViewProperties(timestamp, this._currentPageview?.pageViewId);
2535
+ }
2536
+ doEvent() {
2537
+ return {
2538
+ $pageview_id: this._currentPageview?.pageViewId
2539
+ };
2540
+ }
2541
+ _previousPageViewProperties(timestamp, pageviewId) {
2542
+ const previousPageView = this._currentPageview;
2543
+ if (!previousPageView) {
2544
+ return {
2545
+ $pageview_id: pageviewId
2546
+ };
2547
+ }
2548
+ let properties = {
2549
+ $pageview_id: pageviewId,
2550
+ $prev_pageview_id: previousPageView.pageViewId
2551
+ };
2552
+ const scrollContext = this._instance.scrollManager.getContext();
2553
+ if (scrollContext && !this._instance.config.disable_scroll_properties) {
2554
+ let {
2555
+ maxScrollHeight,
2556
+ lastScrollY,
2557
+ maxScrollY,
2558
+ maxContentHeight,
2559
+ lastContentY,
2560
+ maxContentY
2561
+ } = scrollContext;
2562
+ if (!core.isUndefined(maxScrollHeight) && !core.isUndefined(lastScrollY) && !core.isUndefined(maxScrollY) && !core.isUndefined(maxContentHeight) && !core.isUndefined(lastContentY) && !core.isUndefined(maxContentY)) {
2563
+ // Use ceil, so that e.g. scrolling 999.5px of a 1000px page is considered 100% scrolled
2564
+ maxScrollHeight = Math.ceil(maxScrollHeight);
2565
+ lastScrollY = Math.ceil(lastScrollY);
2566
+ maxScrollY = Math.ceil(maxScrollY);
2567
+ maxContentHeight = Math.ceil(maxContentHeight);
2568
+ lastContentY = Math.ceil(lastContentY);
2569
+ maxContentY = Math.ceil(maxContentY);
2570
+ // if the maximum scroll height is near 0, then the percentage is 1
2571
+ const lastScrollPercentage = maxScrollHeight <= 1 ? 1 : core.clampToRange(lastScrollY / maxScrollHeight, 0, 1, logger);
2572
+ const maxScrollPercentage = maxScrollHeight <= 1 ? 1 : core.clampToRange(maxScrollY / maxScrollHeight, 0, 1, logger);
2573
+ const lastContentPercentage = maxContentHeight <= 1 ? 1 : core.clampToRange(lastContentY / maxContentHeight, 0, 1, logger);
2574
+ const maxContentPercentage = maxContentHeight <= 1 ? 1 : core.clampToRange(maxContentY / maxContentHeight, 0, 1, logger);
2575
+ properties = extend(properties, {
2576
+ $prev_pageview_last_scroll: lastScrollY,
2577
+ $prev_pageview_last_scroll_percentage: lastScrollPercentage,
2578
+ $prev_pageview_max_scroll: maxScrollY,
2579
+ $prev_pageview_max_scroll_percentage: maxScrollPercentage,
2580
+ $prev_pageview_last_content: lastContentY,
2581
+ $prev_pageview_last_content_percentage: lastContentPercentage,
2582
+ $prev_pageview_max_content: maxContentY,
2583
+ $prev_pageview_max_content_percentage: maxContentPercentage
2584
+ });
2585
+ }
2586
+ }
2587
+ if (previousPageView.pathname) {
2588
+ properties.$prev_pageview_pathname = previousPageView.pathname;
2589
+ }
2590
+ if (previousPageView.timestamp) {
2591
+ // Use seconds, for consistency with our other duration-related properties like $duration
2592
+ properties.$prev_pageview_duration = (timestamp.getTime() - previousPageView.timestamp.getTime()) / 1000;
2593
+ }
2594
+ return properties;
2595
+ }
2596
+ }
2597
+
2598
+ // This class is responsible for tracking scroll events and maintaining the scroll context
2599
+ class ScrollManager {
2600
+ constructor(_instance) {
2601
+ this._instance = _instance;
2602
+ this._updateScrollData = () => {
2603
+ if (!this._context) {
2604
+ this._context = {};
2605
+ }
2606
+ const el = this.scrollElement();
2607
+ const scrollY = this.scrollY();
2608
+ const scrollHeight = el ? Math.max(0, el.scrollHeight - el.clientHeight) : 0;
2609
+ const contentY = scrollY + (el?.clientHeight || 0);
2610
+ const contentHeight = el?.scrollHeight || 0;
2611
+ this._context.lastScrollY = Math.ceil(scrollY);
2612
+ this._context.maxScrollY = Math.max(scrollY, this._context.maxScrollY ?? 0);
2613
+ this._context.maxScrollHeight = Math.max(scrollHeight, this._context.maxScrollHeight ?? 0);
2614
+ this._context.lastContentY = contentY;
2615
+ this._context.maxContentY = Math.max(contentY, this._context.maxContentY ?? 0);
2616
+ this._context.maxContentHeight = Math.max(contentHeight, this._context.maxContentHeight ?? 0);
2617
+ };
2618
+ }
2619
+ getContext() {
2620
+ return this._context;
2621
+ }
2622
+ resetContext() {
2623
+ const ctx = this._context;
2624
+ // update the scroll properties for the new page, but wait until the next tick
2625
+ // of the event loop
2626
+ setTimeout(this._updateScrollData, 0);
2627
+ return ctx;
2628
+ }
2629
+ // `capture: true` is required to get scroll events for other scrollable elements
2630
+ // on the page, not just the window
2631
+ // see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#usecapture
2632
+ startMeasuringScrollPosition() {
2633
+ addEventListener(win, 'scroll', this._updateScrollData, {
2634
+ capture: true
2635
+ });
2636
+ addEventListener(win, 'scrollend', this._updateScrollData, {
2637
+ capture: true
2638
+ });
2639
+ addEventListener(win, 'resize', this._updateScrollData);
2640
+ }
2641
+ scrollElement() {
2642
+ if (this._instance.config.scroll_root_selector) {
2643
+ const selectors = core.isArray(this._instance.config.scroll_root_selector) ? this._instance.config.scroll_root_selector : [this._instance.config.scroll_root_selector];
2644
+ for (const selector of selectors) {
2645
+ const element = win?.document.querySelector(selector);
2646
+ if (element) {
2647
+ return element;
49
2648
  }
50
- } catch (err) {
51
- logger.warn('Failed to load persisted data', err);
52
2649
  }
2650
+ return undefined;
2651
+ } else {
2652
+ return win?.document.documentElement;
2653
+ }
2654
+ }
2655
+ scrollY() {
2656
+ if (this._instance.config.scroll_root_selector) {
2657
+ const element = this.scrollElement();
2658
+ return element && element.scrollTop || 0;
2659
+ } else {
2660
+ return win ? win.scrollY || win.pageYOffset || win.document.documentElement.scrollTop || 0 : 0;
2661
+ }
2662
+ }
2663
+ scrollX() {
2664
+ if (this._instance.config.scroll_root_selector) {
2665
+ const element = this.scrollElement();
2666
+ return element && element.scrollLeft || 0;
2667
+ } else {
2668
+ return win ? win.scrollX || win.pageXOffset || win.document.documentElement.scrollLeft || 0 : 0;
2669
+ }
2670
+ }
2671
+ }
2672
+
2673
+ const DEFAULT_BLOCKED_UA_STRS = [
2674
+ // Random assortment of bots
2675
+ 'amazonbot', 'amazonproductbot', 'app.hypefactors.com',
2676
+ // Buck, but "buck" is too short to be safe to block (https://app.hypefactors.com/media-monitoring/about.htm)
2677
+ 'applebot', 'archive.org_bot', 'awariobot', 'backlinksextendedbot', 'baiduspider', 'bingbot', 'bingpreview', 'chrome-lighthouse', 'dataforseobot', 'deepscan', 'duckduckbot', 'facebookexternal', 'facebookcatalog', 'http://yandex.com/bots', 'hubspot', 'ia_archiver', 'leikibot', 'linkedinbot', 'meta-externalagent', 'mj12bot', 'msnbot', 'nessus', 'petalbot', 'pinterest', 'prerender', 'rogerbot', 'screaming frog', 'sebot-wa', 'sitebulb', 'slackbot', 'slurp', 'trendictionbot', 'turnitin', 'twitterbot', 'vercel-screenshot', 'vercelbot', 'yahoo! slurp', 'yandexbot', 'zoombot',
2678
+ // Bot-like words, maybe we should block `bot` entirely?
2679
+ 'bot.htm', 'bot.php', '(bot;', 'bot/', 'crawler',
2680
+ // Ahrefs: https://ahrefs.com/seo/glossary/ahrefsbot
2681
+ 'ahrefsbot', 'ahrefssiteaudit',
2682
+ // Semrush bots: https://www.semrush.com/bot/
2683
+ 'semrushbot', 'siteauditbot', 'splitsignalbot',
2684
+ // AI Crawlers
2685
+ 'gptbot', 'oai-searchbot', 'chatgpt-user', 'perplexitybot',
2686
+ // Uptime-like stuff
2687
+ 'better uptime bot', 'sentryuptimebot', 'uptimerobot',
2688
+ // headless browsers
2689
+ 'headlesschrome', 'cypress',
2690
+ // we don't block electron here, as many customers use posthog-js in electron apps
2691
+ // a whole bunch of goog-specific crawlers
2692
+ // https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers
2693
+ 'google-hoteladsverifier', 'adsbot-google', 'apis-google', 'duplexweb-google', 'feedfetcher-google', 'google favicon', 'google web preview', 'google-read-aloud', 'googlebot', 'googleother', 'google-cloudvertexbot', 'googleweblight', 'mediapartners-google', 'storebot-google', 'google-inspectiontool', 'bytespider'];
2694
+ /**
2695
+ * Block various web spiders from executing our JS and sending false capturing data
2696
+ */
2697
+ const isBlockedUA = function (ua, customBlockedUserAgents) {
2698
+ if (!ua) {
2699
+ return false;
2700
+ }
2701
+ const uaLower = ua.toLowerCase();
2702
+ return DEFAULT_BLOCKED_UA_STRS.concat(customBlockedUserAgents || []).some(blockedUA => {
2703
+ const blockedUaLower = blockedUA.toLowerCase();
2704
+ // can't use includes because IE 11 :/
2705
+ return uaLower.indexOf(blockedUaLower) !== -1;
2706
+ });
2707
+ };
2708
+ const isLikelyBot = function (navigator, customBlockedUserAgents) {
2709
+ if (!navigator) {
2710
+ return false;
2711
+ }
2712
+ const ua = navigator.userAgent;
2713
+ if (ua) {
2714
+ if (isBlockedUA(ua, customBlockedUserAgents)) {
2715
+ return true;
2716
+ }
2717
+ }
2718
+ try {
2719
+ // eslint-disable-next-line compat/compat
2720
+ const uaData = navigator?.userAgentData;
2721
+ if (uaData?.brands && uaData.brands.some(brandObj => isBlockedUA(brandObj?.brand, customBlockedUserAgents))) {
2722
+ return true;
53
2723
  }
54
- logger.info('Leanbase initialized', {
55
- apiKey,
56
- host: leanbaseOptions.host
2724
+ } catch {
2725
+ // ignore the error, we were using experimental browser features
2726
+ }
2727
+ return !!navigator.webdriver;
2728
+ // There's some more enhancements we could make in this area, e.g. it's possible to check if Chrome dev tools are
2729
+ // open, which will detect some bots that are trying to mask themselves and might get past the checks above.
2730
+ // However, this would give false positives for actual humans who have dev tools open.
2731
+ // We could also use the data in navigator.userAgentData.getHighEntropyValues() to detect bots, but we should wait
2732
+ // until this stops being experimental. The MDN docs imply that this might eventually require user permission.
2733
+ // See https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/getHighEntropyValues
2734
+ // It would be very bad if posthog-js caused a permission prompt to appear on every page load.
2735
+ };
2736
+
2737
+ const defaultConfig = () => ({
2738
+ host: 'https://i.leanbase.co',
2739
+ token: '',
2740
+ autocapture: true,
2741
+ rageclick: true,
2742
+ persistence: 'localStorage+cookie',
2743
+ capture_pageview: 'history_change',
2744
+ capture_pageleave: 'if_capture_pageview',
2745
+ persistence_name: '',
2746
+ mask_all_element_attributes: false,
2747
+ cookie_expiration: 365,
2748
+ cross_subdomain_cookie: isCrossDomainCookie(document?.location),
2749
+ custom_campaign_params: [],
2750
+ custom_personal_data_properties: [],
2751
+ disable_persistence: false,
2752
+ mask_personal_data_properties: false,
2753
+ secure_cookie: window?.location?.protocol === 'https:',
2754
+ mask_all_text: false,
2755
+ bootstrap: {},
2756
+ session_idle_timeout_seconds: 30 * 60,
2757
+ save_campaign_params: true,
2758
+ save_referrer: true,
2759
+ opt_out_useragent_filter: false,
2760
+ properties_string_max_length: 65535,
2761
+ loaded: () => {}
2762
+ });
2763
+ class Leanbase extends core.PostHogCore {
2764
+ constructor(token, config) {
2765
+ const mergedConfig = extend(defaultConfig(), config || {}, {
2766
+ token
57
2767
  });
58
- // Preload feature flags if not explicitly disabled
59
- if (options?.preloadFeatureFlags !== false) {
2768
+ super(token, mergedConfig);
2769
+ this.personProcessingSetOncePropertiesSent = false;
2770
+ this.isLoaded = false;
2771
+ this.config = mergedConfig;
2772
+ this.visibilityStateListener = null;
2773
+ this.initialPageviewCaptured = false;
2774
+ this.scrollManager = new ScrollManager(this);
2775
+ this.pageViewManager = new PageViewManager(this);
2776
+ this.init(token, mergedConfig);
2777
+ }
2778
+ init(token, config) {
2779
+ this.setConfig(extend(defaultConfig(), config, {
2780
+ token
2781
+ }));
2782
+ this.isLoaded = true;
2783
+ this.persistence = new LeanbasePersistence(this.config);
2784
+ this.replayAutocapture = new Autocapture(this);
2785
+ this.replayAutocapture.startIfEnabled();
2786
+ if (this.config.preloadFeatureFlags !== false) {
60
2787
  this.reloadFeatureFlags();
61
2788
  }
2789
+ this.config.loaded?.(this);
2790
+ if (this.config.capture_pageview) {
2791
+ setTimeout(() => {
2792
+ if (this.config.cookieless_mode === 'always') {
2793
+ this.captureInitialPageview();
2794
+ }
2795
+ }, 1);
2796
+ }
2797
+ addEventListener(document, 'DOMContentLoaded', () => {
2798
+ this.loadRemoteConfig();
2799
+ });
2800
+ addEventListener(window, 'onpagehide' in self ? 'pagehide' : 'unload', this.capturePageLeave.bind(this), {
2801
+ passive: false
2802
+ });
2803
+ }
2804
+ captureInitialPageview() {
2805
+ if (!document) {
2806
+ return;
2807
+ }
2808
+ if (document.visibilityState !== 'visible') {
2809
+ if (!this.visibilityStateListener) {
2810
+ this.visibilityStateListener = this.captureInitialPageview.bind(this);
2811
+ addEventListener(document, 'visibilitychange', this.visibilityStateListener);
2812
+ }
2813
+ return;
2814
+ }
2815
+ if (!this.initialPageviewCaptured) {
2816
+ this.initialPageviewCaptured = true;
2817
+ this.capture('$pageview', {
2818
+ title: document.title
2819
+ });
2820
+ if (this.visibilityStateListener) {
2821
+ document.removeEventListener('visibilitychange', this.visibilityStateListener);
2822
+ this.visibilityStateListener = null;
2823
+ }
2824
+ }
2825
+ }
2826
+ capturePageLeave() {
2827
+ const {
2828
+ capture_pageleave,
2829
+ capture_pageview
2830
+ } = this.config;
2831
+ if (capture_pageleave === true || capture_pageleave === 'if_capture_pageview' && (capture_pageview === true || capture_pageview === 'history_change')) {
2832
+ this.capture('$pageleave');
2833
+ }
2834
+ }
2835
+ async loadRemoteConfig() {
2836
+ if (!this.isRemoteConfigLoaded) {
2837
+ const remoteConfig = await this.reloadRemoteConfigAsync();
2838
+ if (remoteConfig) {
2839
+ this.onRemoteConfig(remoteConfig);
2840
+ }
2841
+ }
2842
+ }
2843
+ onRemoteConfig(config) {
2844
+ if (!(document && document.body)) {
2845
+ setTimeout(() => {
2846
+ this.onRemoteConfig(config);
2847
+ }, 500);
2848
+ return;
2849
+ }
2850
+ this.isRemoteConfigLoaded = true;
2851
+ this.replayAutocapture?.onRemoteConfig(config);
62
2852
  }
63
- // PostHogCore abstract methods
64
2853
  fetch(url, options) {
65
2854
  const fetchFn = core.getFetch();
66
2855
  if (!fetchFn) {
@@ -68,49 +2857,176 @@ class Leanbase extends core.PostHogCore {
68
2857
  }
69
2858
  return fetchFn(url, options);
70
2859
  }
2860
+ setConfig(config) {
2861
+ const oldConfig = {
2862
+ ...this.config
2863
+ };
2864
+ if (core.isObject(config)) {
2865
+ extend(this.config, config);
2866
+ this.persistence?.update_config(this.config, oldConfig);
2867
+ this.replayAutocapture?.startIfEnabled();
2868
+ }
2869
+ const isTempStorage = this.config.persistence === 'sessionStorage' || this.config.persistence === 'memory';
2870
+ this.sessionPersistence = isTempStorage ? this.persistence : new LeanbasePersistence({
2871
+ ...this.config,
2872
+ persistence: 'sessionStorage'
2873
+ });
2874
+ }
71
2875
  getLibraryId() {
72
2876
  return 'leanbase';
73
2877
  }
74
2878
  getLibraryVersion() {
75
- return version;
2879
+ return Config.LIB_VERSION;
76
2880
  }
77
2881
  getCustomUserAgent() {
78
2882
  return;
79
2883
  }
80
2884
  getPersistedProperty(key) {
81
- return this._storage.get(key);
2885
+ return this.persistence?.get_property(key);
82
2886
  }
83
2887
  setPersistedProperty(key, value) {
84
- if (core.isNull(value)) {
85
- this._storage.delete(key);
86
- } else {
87
- this._storage.set(key, value);
2888
+ this.persistence?.set_property(key, value);
2889
+ }
2890
+ calculateEventProperties(eventName, eventProperties, timestamp, uuid, readOnly) {
2891
+ if (!this.persistence || !this.sessionPersistence) {
2892
+ return eventProperties;
88
2893
  }
89
- // Persist to localStorage if available
90
- if (typeof window !== 'undefined' && window.localStorage) {
91
- try {
92
- const obj = {};
93
- this._storage.forEach((v, k) => {
94
- obj[k] = v;
95
- });
96
- window.localStorage.setItem(this._storageKey, JSON.stringify(obj));
97
- } catch (err) {
98
- logger.warn('Failed to persist data', err);
2894
+ timestamp = timestamp || new Date();
2895
+ const startTimestamp = readOnly ? undefined : this.persistence?.remove_event_timer(eventName);
2896
+ let properties = {
2897
+ ...eventProperties
2898
+ };
2899
+ properties['token'] = this.config.token;
2900
+ if (this.config.cookieless_mode == 'always' || this.config.cookieless_mode == 'on_reject') {
2901
+ properties[COOKIELESS_MODE_FLAG_PROPERTY] = true;
2902
+ }
2903
+ if (eventName === '$snapshot') {
2904
+ const persistenceProps = {
2905
+ ...this.persistence.properties()
2906
+ };
2907
+ properties['distinct_id'] = persistenceProps.distinct_id;
2908
+ if (!(core.isString(properties['distinct_id']) || core.isNumber(properties['distinct_id'])) || core.isEmptyString(properties['distinct_id'])) {
2909
+ logger.error('Invalid distinct_id for replay event. This indicates a bug in your implementation');
99
2910
  }
2911
+ return properties;
2912
+ }
2913
+ const infoProperties = getEventProperties(this.config.mask_personal_data_properties, this.config.custom_personal_data_properties);
2914
+ if (this.sessionManager) {
2915
+ const {
2916
+ sessionId,
2917
+ windowId
2918
+ } = this.sessionManager.checkAndGetSessionAndWindowId(readOnly, timestamp.getTime());
2919
+ properties['$session_id'] = sessionId;
2920
+ properties['$window_id'] = windowId;
2921
+ }
2922
+ if (this.sessionPropsManager) {
2923
+ extend(properties, this.sessionPropsManager.getSessionProps());
2924
+ }
2925
+ let pageviewProperties = this.pageViewManager.doEvent();
2926
+ if (eventName === '$pageview' && !readOnly) {
2927
+ pageviewProperties = this.pageViewManager.doPageView(timestamp, uuid);
2928
+ }
2929
+ if (eventName === '$pageleave' && !readOnly) {
2930
+ pageviewProperties = this.pageViewManager.doPageLeave(timestamp);
2931
+ }
2932
+ properties = extend(properties, pageviewProperties);
2933
+ if (eventName === '$pageview' && document) {
2934
+ properties['title'] = document.title;
2935
+ }
2936
+ if (!core.isUndefined(startTimestamp)) {
2937
+ const duration_in_ms = timestamp.getTime() - startTimestamp;
2938
+ properties['$duration'] = parseFloat((duration_in_ms / 1000).toFixed(3));
2939
+ }
2940
+ if (userAgent && this.config.opt_out_useragent_filter) {
2941
+ properties['$browser_type'] = isLikelyBot(navigator$1, []) ? 'bot' : 'browser';
2942
+ }
2943
+ properties = extend({}, infoProperties, this.persistence.properties(), this.sessionPersistence.properties(), properties);
2944
+ properties['$is_identified'] = this.isIdentified();
2945
+ return properties;
2946
+ }
2947
+ isIdentified() {
2948
+ return this.persistence?.get_property(USER_STATE) === 'identified' || this.sessionPersistence?.get_property(USER_STATE) === 'identified';
2949
+ }
2950
+ /**
2951
+ * Add additional set_once properties to the event when creating a person profile. This allows us to create the
2952
+ * profile with mostly-accurate properties, despite earlier events not setting them. We do this by storing them in
2953
+ * persistence.
2954
+ * @param dataSetOnce
2955
+ */
2956
+ calculateSetOnceProperties(dataSetOnce) {
2957
+ if (!this.persistence) {
2958
+ return dataSetOnce;
2959
+ }
2960
+ if (this.personProcessingSetOncePropertiesSent) {
2961
+ return dataSetOnce;
2962
+ }
2963
+ const initialProps = this.persistence.get_initial_props();
2964
+ const sessionProps = this.sessionPropsManager?.getSetOnceProps();
2965
+ const setOnceProperties = extend({}, initialProps, sessionProps || {}, dataSetOnce || {});
2966
+ this.personProcessingSetOncePropertiesSent = true;
2967
+ if (core.isEmptyObject(setOnceProperties)) {
2968
+ return undefined;
100
2969
  }
2970
+ return setOnceProperties;
101
2971
  }
102
- // Public API: leanbase.capture()
103
2972
  capture(event, properties, options) {
104
- super.capture(event, properties, options);
2973
+ if (!this.isLoaded || !this.sessionPersistence || !this.persistence) {
2974
+ return;
2975
+ }
2976
+ if (core.isUndefined(event) || !core.isString(event)) {
2977
+ logger.error('No event name provided to posthog.capture');
2978
+ return;
2979
+ }
2980
+ if (properties?.$current_url && !core.isString(properties?.$current_url)) {
2981
+ logger.error('Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value.');
2982
+ delete properties?.$current_url;
2983
+ }
2984
+ this.sessionPersistence.update_search_keyword();
2985
+ if (this.config.save_campaign_params) {
2986
+ this.sessionPersistence.update_campaign_params();
2987
+ }
2988
+ if (this.config.save_referrer) {
2989
+ this.sessionPersistence.update_referrer_info();
2990
+ }
2991
+ if (this.config.save_campaign_params || this.config.save_referrer) {
2992
+ this.persistence.set_initial_person_info();
2993
+ }
2994
+ const systemTime = new Date();
2995
+ const timestamp = options?.timestamp || systemTime;
2996
+ const uuid = uuidv7();
2997
+ let data = {
2998
+ uuid,
2999
+ event,
3000
+ properties: this.calculateEventProperties(event, properties || {}, timestamp, uuid)
3001
+ };
3002
+ const setProperties = options?.$set;
3003
+ if (setProperties) {
3004
+ data.$set = options?.$set;
3005
+ }
3006
+ const setOnceProperties = this.calculateSetOnceProperties(options?.$set_once);
3007
+ if (setOnceProperties) {
3008
+ data.$set_once = setOnceProperties;
3009
+ }
3010
+ data = copyAndTruncateStrings(data, options?._noTruncate ? null : this.config.properties_string_max_length);
3011
+ data.timestamp = timestamp;
3012
+ if (!core.isUndefined(options?.timestamp)) {
3013
+ data.properties['$event_time_override_provided'] = true;
3014
+ data.properties['$event_time_override_system_time'] = systemTime;
3015
+ }
3016
+ const finalSet = {
3017
+ ...data.properties['$set'],
3018
+ ...data['$set']
3019
+ };
3020
+ if (!core.isEmptyObject(finalSet)) {
3021
+ this.setPersonPropertiesForFlags(finalSet);
3022
+ }
3023
+ super.capture(data.event, data.properties, options);
105
3024
  }
106
- // Public API: leanbase.identify()
107
3025
  identify(distinctId, properties, options) {
108
3026
  super.identify(distinctId, properties, options);
109
3027
  }
110
- // Cleanup
111
3028
  destroy() {
112
- // Future: cleanup autocapture and session recording
113
- this._storage.clear();
3029
+ this.persistence?.clear();
114
3030
  }
115
3031
  }
116
3032