@leanbase.com/js 0.1.2 → 0.2.0-alpha.0

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