@leanbase.com/js 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -102,8 +102,8 @@ var leanbase = (function () {
102
102
  * @license Apache-2.0
103
103
  * @copyright 2021-2023 LiosK
104
104
  * @packageDocumentation
105
- */ const DIGITS = "0123456789abcdef";
106
- class UUID {
105
+ */ const DIGITS$1 = "0123456789abcdef";
106
+ let UUID$1 = class UUID {
107
107
  constructor(bytes){
108
108
  this.bytes = bytes;
109
109
  }
@@ -164,8 +164,8 @@ var leanbase = (function () {
164
164
  toString() {
165
165
  let text = "";
166
166
  for(let i = 0; i < this.bytes.length; i++){
167
- text += DIGITS.charAt(this.bytes[i] >>> 4);
168
- text += DIGITS.charAt(0xf & this.bytes[i]);
167
+ text += DIGITS$1.charAt(this.bytes[i] >>> 4);
168
+ text += DIGITS$1.charAt(0xf & this.bytes[i]);
169
169
  if (3 === i || 5 === i || 7 === i || 9 === i) text += "-";
170
170
  }
171
171
  return text;
@@ -173,8 +173,8 @@ var leanbase = (function () {
173
173
  toHex() {
174
174
  let text = "";
175
175
  for(let i = 0; i < this.bytes.length; i++){
176
- text += DIGITS.charAt(this.bytes[i] >>> 4);
177
- text += DIGITS.charAt(0xf & this.bytes[i]);
176
+ text += DIGITS$1.charAt(this.bytes[i] >>> 4);
177
+ text += DIGITS$1.charAt(0xf & this.bytes[i]);
178
178
  }
179
179
  return text;
180
180
  }
@@ -206,8 +206,8 @@ var leanbase = (function () {
206
206
  }
207
207
  return 0;
208
208
  }
209
- }
210
- class V7Generator {
209
+ };
210
+ let V7Generator$1 = class V7Generator {
211
211
  constructor(randomNumberGenerator){
212
212
  this.timestamp = 0;
213
213
  this.counter = 0;
@@ -242,7 +242,7 @@ var leanbase = (function () {
242
242
  this.resetCounter();
243
243
  }
244
244
  }
245
- return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & 2 ** 30 - 1, this.random.nextUint32());
245
+ return UUID$1.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & 2 ** 30 - 1, this.random.nextUint32());
246
246
  }
247
247
  resetCounter() {
248
248
  this.counter = 0x400 * this.random.nextUint32() + (0x3ff & this.random.nextUint32());
@@ -251,15 +251,15 @@ var leanbase = (function () {
251
251
  const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
252
252
  bytes[6] = 0x40 | bytes[6] >>> 4;
253
253
  bytes[8] = 0x80 | bytes[8] >>> 2;
254
- return UUID.ofInner(bytes);
254
+ return UUID$1.ofInner(bytes);
255
255
  }
256
- }
256
+ };
257
257
  const getDefaultRandom = ()=>({
258
258
  nextUint32: ()=>0x10000 * Math.trunc(0x10000 * Math.random()) + Math.trunc(0x10000 * Math.random())
259
259
  });
260
- let defaultGenerator;
261
- const uuidv7 = ()=>uuidv7obj().toString();
262
- const uuidv7obj = ()=>(defaultGenerator || (defaultGenerator = new V7Generator())).generate();
260
+ let defaultGenerator$1;
261
+ const uuidv7$1 = ()=>uuidv7obj$1().toString();
262
+ const uuidv7obj$1 = ()=>(defaultGenerator$1 || (defaultGenerator$1 = new V7Generator$1())).generate();
263
263
 
264
264
  var types_PostHogPersistedProperty = /*#__PURE__*/ function(PostHogPersistedProperty) {
265
265
  PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
@@ -295,19 +295,58 @@ var leanbase = (function () {
295
295
  return Compression;
296
296
  }({});
297
297
 
298
+ function includes(str, needle) {
299
+ return -1 !== str.indexOf(needle);
300
+ }
301
+ const trim = function(str) {
302
+ return str.trim();
303
+ };
304
+ const stripLeadingDollar = function(s) {
305
+ return s.replace(/^\$/, '');
306
+ };
307
+
298
308
  const nativeIsArray = Array.isArray;
299
309
  const ObjProto = Object.prototype;
310
+ const type_utils_hasOwnProperty = ObjProto.hasOwnProperty;
300
311
  const type_utils_toString = ObjProto.toString;
301
312
  const isArray = nativeIsArray || function(obj) {
302
313
  return '[object Array]' === type_utils_toString.call(obj);
303
314
  };
304
315
  const isFunction = (x)=>'function' == typeof x;
316
+ const isObject = (x)=>x === Object(x) && !isArray(x);
317
+ const isEmptyObject = (x)=>{
318
+ if (isObject(x)) {
319
+ for(const key in x)if (type_utils_hasOwnProperty.call(x, key)) return false;
320
+ return true;
321
+ }
322
+ return false;
323
+ };
324
+ const isUndefined = (x)=>void 0 === x;
325
+ const isString = (x)=>'[object String]' == type_utils_toString.call(x);
326
+ const isEmptyString = (x)=>isString(x) && 0 === x.trim().length;
305
327
  const isNull = (x)=>null === x;
328
+ const isNullish = (x)=>isUndefined(x) || isNull(x);
329
+ const isNumber = (x)=>'[object Number]' == type_utils_toString.call(x);
330
+ const isBoolean = (x)=>'[object Boolean]' === type_utils_toString.call(x);
331
+ const isFormData = (x)=>x instanceof FormData;
306
332
  const isPlainError = (x)=>x instanceof Error;
307
333
 
334
+ function clampToRange(value, min, max, logger, fallbackValue) {
335
+ if (isNumber(value)) if (value > max) {
336
+ logger.warn(' cannot be greater than max: ' + max + '. Using max value instead.');
337
+ return max;
338
+ } else {
339
+ if (!(value < min)) return value;
340
+ logger.warn(' cannot be less than min: ' + min + '. Using min value instead.');
341
+ return min;
342
+ }
343
+ logger.warn(' must be a number. using max or fallback. max: ' + max + ', fallback: ' + fallbackValue);
344
+ return clampToRange(max, min, max, logger);
345
+ }
346
+
308
347
  class PromiseQueue {
309
348
  add(promise) {
310
- const promiseUUID = uuidv7();
349
+ const promiseUUID = uuidv7$1();
311
350
  this.promiseByIds[promiseUUID] = promise;
312
351
  promise.catch(()=>{}).finally(()=>{
313
352
  delete this.promiseByIds[promiseUUID];
@@ -906,7 +945,7 @@ var leanbase = (function () {
906
945
  library: this.getLibraryId(),
907
946
  library_version: this.getLibraryVersion(),
908
947
  timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
909
- uuid: options?.uuid ? options.uuid : uuidv7()
948
+ uuid: options?.uuid ? options.uuid : uuidv7$1()
910
949
  };
911
950
  const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
912
951
  if (addGeoipDisableProperty) {
@@ -1169,7 +1208,7 @@ var leanbase = (function () {
1169
1208
  const sessionLastDif = now - sessionLastTimestamp;
1170
1209
  const sessionStartDif = now - sessionStartTimestamp;
1171
1210
  if (!sessionId || sessionLastDif > 1000 * this._sessionExpirationTimeSeconds || sessionStartDif > 1000 * this._sessionMaxLengthSeconds) {
1172
- sessionId = uuidv7();
1211
+ sessionId = uuidv7$1();
1173
1212
  this.setPersistedProperty(types_PostHogPersistedProperty.SessionId, sessionId);
1174
1213
  this.setPersistedProperty(types_PostHogPersistedProperty.SessionStartTimestamp, now);
1175
1214
  }
@@ -1187,7 +1226,7 @@ var leanbase = (function () {
1187
1226
  if (!this._isInitialized) return '';
1188
1227
  let anonId = this.getPersistedProperty(types_PostHogPersistedProperty.AnonymousId);
1189
1228
  if (!anonId) {
1190
- anonId = uuidv7();
1229
+ anonId = uuidv7$1();
1191
1230
  this.setPersistedProperty(types_PostHogPersistedProperty.AnonymousId, anonId);
1192
1231
  }
1193
1232
  return anonId;
@@ -1593,173 +1632,3093 @@ var leanbase = (function () {
1593
1632
  }
1594
1633
  }
1595
1634
 
1596
- const version = '0.1.1';
1635
+ const breaker = {};
1636
+ const ArrayProto = Array.prototype;
1637
+ const nativeForEach = ArrayProto.forEach;
1638
+ const nativeIndexOf = ArrayProto.indexOf;
1639
+ const win = typeof window !== 'undefined' ? window : undefined;
1640
+ const global = typeof globalThis !== 'undefined' ? globalThis : win;
1641
+ const navigator$1 = global?.navigator;
1642
+ const document = global?.document;
1643
+ const location = global?.location;
1644
+ global?.fetch;
1645
+ global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined;
1646
+ global?.AbortController;
1647
+ const userAgent = navigator$1?.userAgent;
1648
+ function eachArray(obj, iterator, thisArg) {
1649
+ if (isArray(obj)) {
1650
+ if (nativeForEach && obj.forEach === nativeForEach) {
1651
+ obj.forEach(iterator, thisArg);
1652
+ } else if ('length' in obj && obj.length === +obj.length) {
1653
+ for (let i = 0, l = obj.length; i < l; i++) {
1654
+ if (i in obj && iterator.call(thisArg, obj[i], i) === breaker) {
1655
+ return;
1656
+ }
1657
+ }
1658
+ }
1659
+ }
1660
+ }
1661
+ /**
1662
+ * @param {*=} obj
1663
+ * @param {function(...*)=} iterator
1664
+ * @param {Object=} thisArg
1665
+ */
1666
+ function each(obj, iterator, thisArg) {
1667
+ if (isNullish(obj)) {
1668
+ return;
1669
+ }
1670
+ if (isArray(obj)) {
1671
+ return eachArray(obj, iterator, thisArg);
1672
+ }
1673
+ if (isFormData(obj)) {
1674
+ for (const pair of obj.entries()) {
1675
+ if (iterator.call(thisArg, pair[1], pair[0]) === breaker) {
1676
+ return;
1677
+ }
1678
+ }
1679
+ return;
1680
+ }
1681
+ for (const key in obj) {
1682
+ if (type_utils_hasOwnProperty.call(obj, key)) {
1683
+ if (iterator.call(thisArg, obj[key], key) === breaker) {
1684
+ return;
1685
+ }
1686
+ }
1687
+ }
1688
+ }
1689
+ const extend = function (obj, ...args) {
1690
+ eachArray(args, function (source) {
1691
+ for (const prop in source) {
1692
+ if (source[prop] !== void 0) {
1693
+ obj[prop] = source[prop];
1694
+ }
1695
+ }
1696
+ });
1697
+ return obj;
1698
+ };
1699
+ const extendArray = function (obj, ...args) {
1700
+ eachArray(args, function (source) {
1701
+ eachArray(source, function (item) {
1702
+ obj.push(item);
1703
+ });
1704
+ });
1705
+ return obj;
1706
+ };
1707
+ const include = function (obj, target) {
1708
+ let found = false;
1709
+ if (isNull(obj)) {
1710
+ return found;
1711
+ }
1712
+ if (nativeIndexOf && obj.indexOf === nativeIndexOf) {
1713
+ return obj.indexOf(target) != -1;
1714
+ }
1715
+ each(obj, function (value) {
1716
+ if (found || (found = value === target)) {
1717
+ return breaker;
1718
+ }
1719
+ return;
1720
+ });
1721
+ return found;
1722
+ };
1723
+ /**
1724
+ * Object.entries() polyfill
1725
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
1726
+ */
1727
+ function entries(obj) {
1728
+ const ownProps = Object.keys(obj);
1729
+ let i = ownProps.length;
1730
+ const resArray = new Array(i); // preallocate the Array
1731
+ while (i--) {
1732
+ resArray[i] = [ownProps[i], obj[ownProps[i]]];
1733
+ }
1734
+ return resArray;
1735
+ }
1736
+ function addEventListener(element, event, callback, options) {
1737
+ const {
1738
+ capture = false,
1739
+ passive = true
1740
+ } = options ?? {};
1741
+ // This is the only place where we are allowed to call this function
1742
+ // because the whole idea is that we should be calling this instead of the built-in one
1743
+ // eslint-disable-next-line posthog-js/no-add-event-listener
1744
+ element?.addEventListener(event, callback, {
1745
+ capture,
1746
+ passive
1747
+ });
1748
+ }
1749
+ const stripEmptyProperties = function (p) {
1750
+ const ret = {};
1751
+ each(p, function (v, k) {
1752
+ if (isString(v) && v.length > 0 || isNumber(v)) {
1753
+ ret[k] = v;
1754
+ }
1755
+ });
1756
+ return ret;
1757
+ };
1758
+ const EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE = ['herokuapp.com', 'vercel.app', 'netlify.app'];
1759
+ function isCrossDomainCookie(documentLocation) {
1760
+ const hostname = documentLocation?.hostname;
1761
+ if (!isString(hostname)) {
1762
+ return false;
1763
+ }
1764
+ // split and slice isn't a great way to match arbitrary domains,
1765
+ // but it's good enough for ensuring we only match herokuapp.com when it is the TLD
1766
+ // for the hostname
1767
+ const lastTwoParts = hostname.split('.').slice(-2).join('.');
1768
+ for (const excluded of EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE) {
1769
+ if (lastTwoParts === excluded) {
1770
+ return false;
1771
+ }
1772
+ }
1773
+ return true;
1774
+ }
1775
+ /**
1776
+ * Deep copies an object.
1777
+ * It handles cycles by replacing all references to them with `undefined`
1778
+ * Also supports customizing native values
1779
+ *
1780
+ * @param value
1781
+ * @param customizer
1782
+ * @returns {{}|undefined|*}
1783
+ */
1784
+ function deepCircularCopy(value, customizer) {
1785
+ const COPY_IN_PROGRESS_SET = new Set();
1786
+ function internalDeepCircularCopy(value, key) {
1787
+ if (value !== Object(value)) return customizer ? customizer(value, key) : value; // primitive value
1788
+ if (COPY_IN_PROGRESS_SET.has(value)) return undefined;
1789
+ COPY_IN_PROGRESS_SET.add(value);
1790
+ let result;
1791
+ if (isArray(value)) {
1792
+ result = [];
1793
+ eachArray(value, it => {
1794
+ result.push(internalDeepCircularCopy(it));
1795
+ });
1796
+ } else {
1797
+ result = {};
1798
+ each(value, (val, key) => {
1799
+ if (!COPY_IN_PROGRESS_SET.has(val)) {
1800
+ result[key] = internalDeepCircularCopy(val, key);
1801
+ }
1802
+ });
1803
+ }
1804
+ return result;
1805
+ }
1806
+ return internalDeepCircularCopy(value);
1807
+ }
1808
+ function copyAndTruncateStrings(object, maxStringLength) {
1809
+ return deepCircularCopy(object, value => {
1810
+ if (isString(value) && !isNull(maxStringLength)) {
1811
+ return value.slice(0, maxStringLength);
1812
+ }
1813
+ return value;
1814
+ });
1815
+ }
1816
+
1817
+ /*
1818
+ * Constants
1819
+ */
1820
+ /* PROPERTY KEYS */
1821
+ // This key is deprecated, but we want to check for it to see whether aliasing is allowed.
1822
+ const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id';
1823
+ const DISTINCT_ID = 'distinct_id';
1824
+ const ALIAS_ID_KEY = '__alias';
1825
+ const CAMPAIGN_IDS_KEY = '__cmpns';
1826
+ const EVENT_TIMERS_KEY = '__timers';
1827
+ const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side';
1828
+ const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side';
1829
+ const ERROR_TRACKING_SUPPRESSION_RULES = '$error_tracking_suppression_rules';
1830
+ // @deprecated can be removed along with eager loaded replay
1831
+ const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side';
1832
+ const SESSION_ID = '$sesid';
1833
+ const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled';
1834
+ const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags';
1835
+ const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features';
1836
+ const PERSISTENCE_FEATURE_FLAG_DETAILS = '$feature_flag_details';
1837
+ const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties';
1838
+ const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties';
1839
+ const SURVEYS = '$surveys';
1840
+ const FLAG_CALL_REPORTED = '$flag_call_reported';
1841
+ const USER_STATE = '$user_state';
1842
+ const CLIENT_SESSION_PROPS = '$client_session_props';
1843
+ const CAPTURE_RATE_LIMIT = '$capture_rate_limit';
1844
+ /** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */
1845
+ const INITIAL_CAMPAIGN_PARAMS = '$initial_campaign_params';
1846
+ /** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */
1847
+ const INITIAL_REFERRER_INFO = '$initial_referrer_info';
1848
+ const INITIAL_PERSON_INFO = '$initial_person_info';
1849
+ const ENABLE_PERSON_PROCESSING = '$epp';
1850
+ const COOKIELESS_MODE_FLAG_PROPERTY = '$cookieless_mode';
1851
+ // These are properties that are reserved and will not be automatically included in events
1852
+ 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,
1853
+ // Ignore posthog persisted properties
1854
+ types_PostHogPersistedProperty.Queue, types_PostHogPersistedProperty.FeatureFlagDetails, types_PostHogPersistedProperty.FlagsEndpointWasHit, types_PostHogPersistedProperty.AnonymousId, types_PostHogPersistedProperty.RemoteConfig, types_PostHogPersistedProperty.Surveys, types_PostHogPersistedProperty.FeatureFlags];
1597
1855
 
1598
- // Simple logger with [Leanbase] prefix
1856
+ /* eslint-disable no-console */
1599
1857
  const PREFIX = '[Leanbase]';
1600
1858
  const logger = {
1601
1859
  info: (...args) => {
1602
1860
  if (typeof console !== 'undefined') {
1603
- // eslint-disable-next-line no-console
1604
1861
  console.log(PREFIX, ...args);
1605
1862
  }
1606
1863
  },
1607
1864
  warn: (...args) => {
1608
1865
  if (typeof console !== 'undefined') {
1609
- // eslint-disable-next-line no-console
1610
1866
  console.warn(PREFIX, ...args);
1611
1867
  }
1612
1868
  },
1613
1869
  error: (...args) => {
1614
1870
  if (typeof console !== 'undefined') {
1615
- // eslint-disable-next-line no-console
1616
1871
  console.error(PREFIX, ...args);
1617
1872
  }
1873
+ },
1874
+ critical: (...args) => {
1875
+ if (typeof console !== 'undefined') {
1876
+ console.error(PREFIX, 'CRITICAL:', ...args);
1877
+ }
1618
1878
  }
1619
1879
  };
1620
1880
 
1621
- class Leanbase extends PostHogCore {
1622
- constructor(apiKey, options) {
1623
- // Leanbase defaults
1624
- const leanbaseOptions = {
1625
- host: 'https://i.leanbase.co',
1626
- ...options
1627
- };
1628
- super(apiKey, leanbaseOptions);
1629
- this._storage = new Map();
1630
- this._storageKey = `leanbase_${apiKey}`;
1631
- // Load from localStorage if available
1632
- if (typeof window !== 'undefined' && window.localStorage) {
1633
- try {
1634
- const stored = window.localStorage.getItem(this._storageKey);
1635
- if (stored) {
1636
- const parsed = JSON.parse(stored);
1637
- Object.entries(parsed).forEach(([key, value]) => {
1638
- this._storage.set(key, value);
1639
- });
1640
- }
1641
- } catch (err) {
1642
- logger.warn('Failed to load persisted data', err);
1643
- }
1644
- }
1645
- logger.info('Leanbase initialized', {
1646
- apiKey,
1647
- host: leanbaseOptions.host
1648
- });
1649
- // Preload feature flags if not explicitly disabled
1650
- if (options?.preloadFeatureFlags !== false) {
1651
- this.reloadFeatureFlags();
1881
+ /**
1882
+ * uuidv7: An experimental implementation of the proposed UUID Version 7
1883
+ *
1884
+ * @license Apache-2.0
1885
+ * @copyright 2021-2023 LiosK
1886
+ * @packageDocumentation
1887
+ *
1888
+ * from https://github.com/LiosK/uuidv7/blob/e501462ea3d23241de13192ceae726956f9b3b7d/src/index.ts
1889
+ */
1890
+ // polyfill for IE11
1891
+ if (!Math.trunc) {
1892
+ Math.trunc = function (v) {
1893
+ return v < 0 ? Math.ceil(v) : Math.floor(v);
1894
+ };
1895
+ }
1896
+ // polyfill for IE11
1897
+ if (!Number.isInteger) {
1898
+ Number.isInteger = function (value) {
1899
+ return isNumber(value) && isFinite(value) && Math.floor(value) === value;
1900
+ };
1901
+ }
1902
+ const DIGITS = '0123456789abcdef';
1903
+ /** Represents a UUID as a 16-byte byte array. */
1904
+ class UUID {
1905
+ /** @param bytes - The 16-byte byte array representation. */
1906
+ constructor(bytes) {
1907
+ this.bytes = bytes;
1908
+ if (bytes.length !== 16) {
1909
+ throw new TypeError('not 128-bit length');
1652
1910
  }
1653
1911
  }
1654
- // PostHogCore abstract methods
1655
- fetch(url, options) {
1656
- const fetchFn = getFetch();
1657
- if (!fetchFn) {
1658
- return Promise.reject(new Error('Fetch API is not available in this environment.'));
1912
+ /**
1913
+ * Builds a byte array from UUIDv7 field values.
1914
+ *
1915
+ * @param unixTsMs - A 48-bit `unix_ts_ms` field value.
1916
+ * @param randA - A 12-bit `rand_a` field value.
1917
+ * @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.
1918
+ * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.
1919
+ */
1920
+ static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {
1921
+ 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) {
1922
+ throw new RangeError('invalid field value');
1923
+ }
1924
+ const bytes = new Uint8Array(16);
1925
+ bytes[0] = unixTsMs / 2 ** 40;
1926
+ bytes[1] = unixTsMs / 2 ** 32;
1927
+ bytes[2] = unixTsMs / 2 ** 24;
1928
+ bytes[3] = unixTsMs / 2 ** 16;
1929
+ bytes[4] = unixTsMs / 2 ** 8;
1930
+ bytes[5] = unixTsMs;
1931
+ bytes[6] = 0x70 | randA >>> 8;
1932
+ bytes[7] = randA;
1933
+ bytes[8] = 0x80 | randBHi >>> 24;
1934
+ bytes[9] = randBHi >>> 16;
1935
+ bytes[10] = randBHi >>> 8;
1936
+ bytes[11] = randBHi;
1937
+ bytes[12] = randBLo >>> 24;
1938
+ bytes[13] = randBLo >>> 16;
1939
+ bytes[14] = randBLo >>> 8;
1940
+ bytes[15] = randBLo;
1941
+ return new UUID(bytes);
1942
+ }
1943
+ /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */
1944
+ toString() {
1945
+ let text = '';
1946
+ for (let i = 0; i < this.bytes.length; i++) {
1947
+ text = text + DIGITS.charAt(this.bytes[i] >>> 4) + DIGITS.charAt(this.bytes[i] & 0xf);
1948
+ if (i === 3 || i === 5 || i === 7 || i === 9) {
1949
+ text += '-';
1950
+ }
1659
1951
  }
1660
- return fetchFn(url, options);
1952
+ if (text.length !== 36) {
1953
+ // We saw one customer whose bundling code was mangling the UUID generation
1954
+ // rather than accept a bad UUID, we throw an error here.
1955
+ throw new Error('Invalid UUIDv7 was generated');
1956
+ }
1957
+ return text;
1661
1958
  }
1662
- getLibraryId() {
1663
- return 'leanbase';
1959
+ /** Creates an object from `this`. */
1960
+ clone() {
1961
+ return new UUID(this.bytes.slice(0));
1664
1962
  }
1665
- getLibraryVersion() {
1666
- return version;
1963
+ /** Returns true if `this` is equivalent to `other`. */
1964
+ equals(other) {
1965
+ return this.compareTo(other) === 0;
1667
1966
  }
1668
- getCustomUserAgent() {
1669
- return;
1967
+ /**
1968
+ * Returns a negative integer, zero, or positive integer if `this` is less
1969
+ * than, equal to, or greater than `other`, respectively.
1970
+ */
1971
+ compareTo(other) {
1972
+ for (let i = 0; i < 16; i++) {
1973
+ const diff = this.bytes[i] - other.bytes[i];
1974
+ if (diff !== 0) {
1975
+ return Math.sign(diff);
1976
+ }
1977
+ }
1978
+ return 0;
1670
1979
  }
1671
- getPersistedProperty(key) {
1672
- return this._storage.get(key);
1980
+ }
1981
+ /** Encapsulates the monotonic counter state. */
1982
+ class V7Generator {
1983
+ constructor() {
1984
+ this._timestamp = 0;
1985
+ this._counter = 0;
1986
+ this._random = new DefaultRandom();
1673
1987
  }
1674
- setPersistedProperty(key, value) {
1675
- if (isNull(value)) {
1676
- this._storage.delete(key);
1988
+ /**
1989
+ * Generates a new UUIDv7 object from the current timestamp, or resets the
1990
+ * generator upon significant timestamp rollback.
1991
+ *
1992
+ * This method returns monotonically increasing UUIDs unless the up-to-date
1993
+ * timestamp is significantly (by ten seconds or more) smaller than the one
1994
+ * embedded in the immediately preceding UUID. If such a significant clock
1995
+ * rollback is detected, this method resets the generator and returns a new
1996
+ * UUID based on the current timestamp.
1997
+ */
1998
+ generate() {
1999
+ const value = this.generateOrAbort();
2000
+ if (!isUndefined(value)) {
2001
+ return value;
1677
2002
  } else {
1678
- this._storage.set(key, value);
2003
+ // reset state and resume
2004
+ this._timestamp = 0;
2005
+ const valueAfterReset = this.generateOrAbort();
2006
+ if (isUndefined(valueAfterReset)) {
2007
+ throw new Error('Could not generate UUID after timestamp reset');
2008
+ }
2009
+ return valueAfterReset;
1679
2010
  }
1680
- // Persist to localStorage if available
1681
- if (typeof window !== 'undefined' && window.localStorage) {
1682
- try {
1683
- const obj = {};
1684
- this._storage.forEach((v, k) => {
1685
- obj[k] = v;
1686
- });
1687
- window.localStorage.setItem(this._storageKey, JSON.stringify(obj));
1688
- } catch (err) {
1689
- logger.warn('Failed to persist data', err);
2011
+ }
2012
+ /**
2013
+ * Generates a new UUIDv7 object from the current timestamp, or returns
2014
+ * `undefined` upon significant timestamp rollback.
2015
+ *
2016
+ * This method returns monotonically increasing UUIDs unless the up-to-date
2017
+ * timestamp is significantly (by ten seconds or more) smaller than the one
2018
+ * embedded in the immediately preceding UUID. If such a significant clock
2019
+ * rollback is detected, this method aborts and returns `undefined`.
2020
+ */
2021
+ generateOrAbort() {
2022
+ const MAX_COUNTER = 4398046511103;
2023
+ const ROLLBACK_ALLOWANCE = 10000; // 10 seconds
2024
+ const ts = Date.now();
2025
+ if (ts > this._timestamp) {
2026
+ this._timestamp = ts;
2027
+ this._resetCounter();
2028
+ } else if (ts + ROLLBACK_ALLOWANCE > this._timestamp) {
2029
+ // go on with previous timestamp if new one is not much smaller
2030
+ this._counter++;
2031
+ if (this._counter > MAX_COUNTER) {
2032
+ // increment timestamp at counter overflow
2033
+ this._timestamp++;
2034
+ this._resetCounter();
1690
2035
  }
2036
+ } else {
2037
+ // abort if clock went backwards to unbearable extent
2038
+ return undefined;
1691
2039
  }
2040
+ return UUID.fromFieldsV7(this._timestamp, Math.trunc(this._counter / 2 ** 30), this._counter & 2 ** 30 - 1, this._random.nextUint32());
1692
2041
  }
1693
- // Public API: leanbase.capture()
1694
- capture(event, properties, options) {
1695
- super.capture(event, properties, options);
2042
+ /** Initializes the counter at a 42-bit random integer. */
2043
+ _resetCounter() {
2044
+ this._counter = this._random.nextUint32() * 0x400 + (this._random.nextUint32() & 0x3ff);
1696
2045
  }
1697
- // Public API: leanbase.identify()
1698
- identify(distinctId, properties, options) {
1699
- super.identify(distinctId, properties, options);
2046
+ }
2047
+ /** Stores `crypto.getRandomValues()` available in the environment. */
2048
+ let getRandomValues = buffer => {
2049
+ // fall back on Math.random() unless the flag is set to true
2050
+ // TRICKY: don't use the isUndefined method here as can't pass the reference
2051
+ if (typeof UUIDV7_DENY_WEAK_RNG !== 'undefined' && UUIDV7_DENY_WEAK_RNG) {
2052
+ throw new Error('no cryptographically strong RNG available');
1700
2053
  }
1701
- // Cleanup
1702
- destroy() {
1703
- // Future: cleanup autocapture and session recording
1704
- this._storage.clear();
2054
+ for (let i = 0; i < buffer.length; i++) {
2055
+ buffer[i] = Math.trunc(Math.random() * 65536) * 65536 + Math.trunc(Math.random() * 65536);
2056
+ }
2057
+ return buffer;
2058
+ };
2059
+ // detect Web Crypto API
2060
+ if (win && !isUndefined(win.crypto) && crypto.getRandomValues) {
2061
+ getRandomValues = buffer => crypto.getRandomValues(buffer);
2062
+ }
2063
+ /**
2064
+ * Wraps `crypto.getRandomValues()` and compatibles to enable buffering; this
2065
+ * uses a small buffer by default to avoid unbearable throughput decline in some
2066
+ * environments as well as the waste of time and space for unused values.
2067
+ */
2068
+ class DefaultRandom {
2069
+ constructor() {
2070
+ this._buffer = new Uint32Array(8);
2071
+ this._cursor = Infinity;
2072
+ }
2073
+ nextUint32() {
2074
+ if (this._cursor >= this._buffer.length) {
2075
+ getRandomValues(this._buffer);
2076
+ this._cursor = 0;
2077
+ }
2078
+ return this._buffer[this._cursor++];
1705
2079
  }
1706
2080
  }
2081
+ let defaultGenerator;
2082
+ /**
2083
+ * Generates a UUIDv7 string.
2084
+ *
2085
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
2086
+ * ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
2087
+ */
2088
+ const uuidv7 = () => uuidv7obj().toString();
2089
+ /** Generates a UUIDv7 object. */
2090
+ const uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
1707
2091
 
1708
- const api = {
1709
- _instance: null,
1710
- _queue: [],
1711
- init(apiKey, options) {
1712
- this._instance = new Leanbase(apiKey, options);
1713
- // Flush queued calls
1714
- const q = this._queue;
1715
- this._queue = [];
1716
- for (const {
1717
- fn,
1718
- args
1719
- } of q) {
1720
- // @ts-expect-error dynamic dispatch to API methods
1721
- this[fn](...args);
2092
+ // we store the discovered subdomain in memory because it might be read multiple times
2093
+ let firstNonPublicSubDomain = '';
2094
+ /**
2095
+ * Browsers don't offer a way to check if something is a public suffix
2096
+ * e.g. `.com.au`, `.io`, `.org.uk`
2097
+ *
2098
+ * But they do reject cookies set on public suffixes
2099
+ * Setting a cookie on `.co.uk` would mean it was sent for every `.co.uk` site visited
2100
+ *
2101
+ * So, we can use this to check if a domain is a public suffix
2102
+ * by trying to set a cookie on a subdomain of the provided hostname
2103
+ * until the browser accepts it
2104
+ *
2105
+ * inspired by https://github.com/AngusFu/browser-root-domain
2106
+ */
2107
+ function seekFirstNonPublicSubDomain(hostname, cookieJar = document) {
2108
+ if (firstNonPublicSubDomain) {
2109
+ return firstNonPublicSubDomain;
2110
+ }
2111
+ if (!cookieJar) {
2112
+ return '';
2113
+ }
2114
+ if (['localhost', '127.0.0.1'].includes(hostname)) return '';
2115
+ const list = hostname.split('.');
2116
+ let len = Math.min(list.length, 8); // paranoia - we know this number should be small
2117
+ const key = 'dmn_chk_' + uuidv7();
2118
+ while (!firstNonPublicSubDomain && len--) {
2119
+ const candidate = list.slice(len).join('.');
2120
+ const candidateCookieValue = key + '=1;domain=.' + candidate + ';path=/';
2121
+ // try to set cookie, include a short expiry in seconds since we'll check immediately
2122
+ cookieJar.cookie = candidateCookieValue + ';max-age=3';
2123
+ if (cookieJar.cookie.includes(key)) {
2124
+ // the cookie was accepted by the browser, remove the test cookie
2125
+ cookieJar.cookie = candidateCookieValue + ';max-age=0';
2126
+ firstNonPublicSubDomain = candidate;
2127
+ }
2128
+ }
2129
+ return firstNonPublicSubDomain;
2130
+ }
2131
+ const DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;
2132
+ const originalCookieDomainFn = hostname => {
2133
+ const matches = hostname.match(DOMAIN_MATCH_REGEX);
2134
+ return matches ? matches[0] : '';
2135
+ };
2136
+ function chooseCookieDomain(hostname, cross_subdomain) {
2137
+ if (cross_subdomain) {
2138
+ // NOTE: Could we use this for cross domain tracking?
2139
+ let matchedSubDomain = seekFirstNonPublicSubDomain(hostname);
2140
+ if (!matchedSubDomain) {
2141
+ const originalMatch = originalCookieDomainFn(hostname);
2142
+ if (originalMatch !== matchedSubDomain) {
2143
+ logger.info('Warning: cookie subdomain discovery mismatch', originalMatch, matchedSubDomain);
2144
+ }
2145
+ matchedSubDomain = originalMatch;
1722
2146
  }
2147
+ return matchedSubDomain ? '; domain=.' + matchedSubDomain : '';
2148
+ }
2149
+ return '';
2150
+ }
2151
+ // Methods partially borrowed from quirksmode.org/js/cookies.html
2152
+ const cookieStore = {
2153
+ _is_supported: () => !!document,
2154
+ _error: function (msg) {
2155
+ logger.error('cookieStore error: ' + msg);
1723
2156
  },
1724
- capture(...args) {
1725
- if (this._instance) {
1726
- this._instance.capture(...args);
1727
- } else {
1728
- this._queue.push({
1729
- fn: 'capture',
1730
- args
1731
- });
2157
+ _get: function (name) {
2158
+ if (!document) {
2159
+ return;
2160
+ }
2161
+ try {
2162
+ const nameEQ = name + '=';
2163
+ const ca = document.cookie.split(';').filter(x => x.length);
2164
+ for (let i = 0; i < ca.length; i++) {
2165
+ let c = ca[i];
2166
+ while (c.charAt(0) == ' ') {
2167
+ c = c.substring(1, c.length);
2168
+ }
2169
+ if (c.indexOf(nameEQ) === 0) {
2170
+ return decodeURIComponent(c.substring(nameEQ.length, c.length));
2171
+ }
2172
+ }
2173
+ } catch {}
2174
+ return null;
2175
+ },
2176
+ _parse: function (name) {
2177
+ let cookie;
2178
+ try {
2179
+ cookie = JSON.parse(cookieStore._get(name)) || {};
2180
+ } catch {
2181
+ // noop
1732
2182
  }
2183
+ return cookie;
1733
2184
  },
1734
- identify(...args) {
1735
- if (this._instance) {
1736
- this._instance.identify(...args);
2185
+ _set: function (name, value, days, cross_subdomain, is_secure) {
2186
+ if (!document) {
2187
+ return;
2188
+ }
2189
+ try {
2190
+ let expires = '',
2191
+ secure = '';
2192
+ const cdomain = chooseCookieDomain(document.location.hostname, cross_subdomain);
2193
+ if (days) {
2194
+ const date = new Date();
2195
+ date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
2196
+ expires = '; expires=' + date.toUTCString();
2197
+ }
2198
+ if (is_secure) {
2199
+ secure = '; secure';
2200
+ }
2201
+ const new_cookie_val = name + '=' + encodeURIComponent(JSON.stringify(value)) + expires + '; SameSite=Lax; path=/' + cdomain + secure;
2202
+ // 4096 bytes is the size at which some browsers (e.g. firefox) will not store a cookie, warn slightly before that
2203
+ if (new_cookie_val.length > 4096 * 0.9) {
2204
+ logger.warn('cookieStore warning: large cookie, len=' + new_cookie_val.length);
2205
+ }
2206
+ document.cookie = new_cookie_val;
2207
+ return new_cookie_val;
2208
+ } catch {
2209
+ return;
2210
+ }
2211
+ },
2212
+ _remove: function (name, cross_subdomain) {
2213
+ if (!document?.cookie) {
2214
+ return;
2215
+ }
2216
+ try {
2217
+ cookieStore._set(name, '', -1, cross_subdomain);
2218
+ } catch {
2219
+ return;
2220
+ }
2221
+ }
2222
+ };
2223
+ let _localStorage_supported = null;
2224
+ const localStore = {
2225
+ _is_supported: function () {
2226
+ if (!isNull(_localStorage_supported)) {
2227
+ return _localStorage_supported;
2228
+ }
2229
+ let supported = true;
2230
+ if (!isUndefined(win)) {
2231
+ try {
2232
+ const key = '__mplssupport__',
2233
+ val = 'xyz';
2234
+ localStore._set(key, val);
2235
+ if (localStore._get(key) !== '"xyz"') {
2236
+ supported = false;
2237
+ }
2238
+ localStore._remove(key);
2239
+ } catch {
2240
+ supported = false;
2241
+ }
1737
2242
  } else {
1738
- this._queue.push({
1739
- fn: 'identify',
1740
- args
2243
+ supported = false;
2244
+ }
2245
+ if (!supported) {
2246
+ logger.error('localStorage unsupported; falling back to cookie store');
2247
+ }
2248
+ _localStorage_supported = supported;
2249
+ return supported;
2250
+ },
2251
+ _error: function (msg) {
2252
+ logger.error('localStorage error: ' + msg);
2253
+ },
2254
+ _get: function (name) {
2255
+ try {
2256
+ return win?.localStorage.getItem(name);
2257
+ } catch (err) {
2258
+ localStore._error(err);
2259
+ }
2260
+ return null;
2261
+ },
2262
+ _parse: function (name) {
2263
+ try {
2264
+ return JSON.parse(localStore._get(name)) || {};
2265
+ } catch {
2266
+ // noop
2267
+ }
2268
+ return null;
2269
+ },
2270
+ _set: function (name, value) {
2271
+ try {
2272
+ win?.localStorage.setItem(name, JSON.stringify(value));
2273
+ } catch (err) {
2274
+ localStore._error(err);
2275
+ }
2276
+ },
2277
+ _remove: function (name) {
2278
+ try {
2279
+ win?.localStorage.removeItem(name);
2280
+ } catch (err) {
2281
+ localStore._error(err);
2282
+ }
2283
+ }
2284
+ };
2285
+ // Use localstorage for most data but still use cookie for COOKIE_PERSISTED_PROPERTIES
2286
+ // This solves issues with cookies having too much data in them causing headers too large
2287
+ // Also makes sure we don't have to send a ton of data to the server
2288
+ const COOKIE_PERSISTED_PROPERTIES = [DISTINCT_ID, SESSION_ID, SESSION_RECORDING_IS_SAMPLED, ENABLE_PERSON_PROCESSING, INITIAL_PERSON_INFO];
2289
+ const localPlusCookieStore = {
2290
+ ...localStore,
2291
+ _parse: function (name) {
2292
+ try {
2293
+ let cookieProperties = {};
2294
+ try {
2295
+ // See if there's a cookie stored with data.
2296
+ cookieProperties = cookieStore._parse(name) || {};
2297
+ } catch {}
2298
+ const value = extend(cookieProperties, JSON.parse(localStore._get(name) || '{}'));
2299
+ localStore._set(name, value);
2300
+ return value;
2301
+ } catch {
2302
+ // noop
2303
+ }
2304
+ return null;
2305
+ },
2306
+ _set: function (name, value, days, cross_subdomain, is_secure, debug) {
2307
+ try {
2308
+ localStore._set(name, value, undefined, undefined, debug);
2309
+ const cookiePersistedProperties = {};
2310
+ COOKIE_PERSISTED_PROPERTIES.forEach(key => {
2311
+ if (value[key]) {
2312
+ cookiePersistedProperties[key] = value[key];
2313
+ }
1741
2314
  });
2315
+ if (Object.keys(cookiePersistedProperties).length) {
2316
+ cookieStore._set(name, cookiePersistedProperties, days, cross_subdomain, is_secure, debug);
2317
+ }
2318
+ } catch (err) {
2319
+ localStore._error(err);
1742
2320
  }
1743
2321
  },
1744
- group(...args) {
1745
- if (this._instance && isFunction(this._instance.group)) {
1746
- this._instance.group(...args);
2322
+ _remove: function (name, cross_subdomain) {
2323
+ try {
2324
+ win?.localStorage.removeItem(name);
2325
+ cookieStore._remove(name, cross_subdomain);
2326
+ } catch (err) {
2327
+ localStore._error(err);
2328
+ }
2329
+ }
2330
+ };
2331
+ const memoryStorage = {};
2332
+ // Storage that only lasts the length of the pageview if we don't want to use cookies
2333
+ const memoryStore = {
2334
+ _is_supported: function () {
2335
+ return true;
2336
+ },
2337
+ _error: function (msg) {
2338
+ logger.error('memoryStorage error: ' + msg);
2339
+ },
2340
+ _get: function (name) {
2341
+ return memoryStorage[name] || null;
2342
+ },
2343
+ _parse: function (name) {
2344
+ return memoryStorage[name] || null;
2345
+ },
2346
+ _set: function (name, value) {
2347
+ memoryStorage[name] = value;
2348
+ },
2349
+ _remove: function (name) {
2350
+ delete memoryStorage[name];
2351
+ }
2352
+ };
2353
+ let sessionStorageSupported = null;
2354
+ // Storage that only lasts the length of a tab/window. Survives page refreshes
2355
+ const sessionStore = {
2356
+ _is_supported: function () {
2357
+ if (!isNull(sessionStorageSupported)) {
2358
+ return sessionStorageSupported;
2359
+ }
2360
+ sessionStorageSupported = true;
2361
+ if (!isUndefined(win)) {
2362
+ try {
2363
+ const key = '__support__',
2364
+ val = 'xyz';
2365
+ sessionStore._set(key, val);
2366
+ if (sessionStore._get(key) !== '"xyz"') {
2367
+ sessionStorageSupported = false;
2368
+ }
2369
+ sessionStore._remove(key);
2370
+ } catch {
2371
+ sessionStorageSupported = false;
2372
+ }
1747
2373
  } else {
1748
- this._queue.push({
1749
- fn: 'group',
1750
- args
1751
- });
2374
+ sessionStorageSupported = false;
1752
2375
  }
2376
+ return sessionStorageSupported;
1753
2377
  },
1754
- alias(...args) {
1755
- if (this._instance && isFunction(this._instance.alias)) {
1756
- this._instance.alias(...args);
2378
+ _error: function (msg) {
2379
+ logger.error('sessionStorage error: ', msg);
2380
+ },
2381
+ _get: function (name) {
2382
+ try {
2383
+ return win?.sessionStorage.getItem(name);
2384
+ } catch (err) {
2385
+ sessionStore._error(err);
2386
+ }
2387
+ return null;
2388
+ },
2389
+ _parse: function (name) {
2390
+ try {
2391
+ return JSON.parse(sessionStore._get(name)) || null;
2392
+ } catch {
2393
+ // noop
2394
+ }
2395
+ return null;
2396
+ },
2397
+ _set: function (name, value) {
2398
+ try {
2399
+ win?.sessionStorage.setItem(name, JSON.stringify(value));
2400
+ } catch (err) {
2401
+ sessionStore._error(err);
2402
+ }
2403
+ },
2404
+ _remove: function (name) {
2405
+ try {
2406
+ win?.sessionStorage.removeItem(name);
2407
+ } catch (err) {
2408
+ sessionStore._error(err);
2409
+ }
2410
+ }
2411
+ };
2412
+
2413
+ /**
2414
+ * IE11 doesn't support `new URL`
2415
+ * so we can create an anchor element and use that to parse the URL
2416
+ * there's a lot of overlap between HTMLHyperlinkElementUtils and URL
2417
+ * meaning useful properties like `pathname` are available on both
2418
+ */
2419
+ const convertToURL = url => {
2420
+ const location = document?.createElement('a');
2421
+ if (isUndefined(location)) {
2422
+ return null;
2423
+ }
2424
+ location.href = url;
2425
+ return location;
2426
+ };
2427
+ // NOTE: Once we get rid of IE11/op_mini we can start using URLSearchParams
2428
+ const getQueryParam = function (url, param) {
2429
+ const withoutHash = url.split('#')[0] || '';
2430
+ // Split only on the first ? to sort problem out for those with multiple ?s
2431
+ // and then remove them
2432
+ const queryParams = withoutHash.split(/\?(.*)/)[1] || '';
2433
+ const cleanedQueryParams = queryParams.replace(/^\?+/g, '');
2434
+ const queryParts = cleanedQueryParams.split('&');
2435
+ let keyValuePair;
2436
+ for (let i = 0; i < queryParts.length; i++) {
2437
+ const parts = queryParts[i].split('=');
2438
+ if (parts[0] === param) {
2439
+ keyValuePair = parts;
2440
+ break;
2441
+ }
2442
+ }
2443
+ if (!isArray(keyValuePair) || keyValuePair.length < 2) {
2444
+ return '';
2445
+ } else {
2446
+ let result = keyValuePair[1];
2447
+ try {
2448
+ result = decodeURIComponent(result);
2449
+ } catch {
2450
+ logger.error('Skipping decoding for malformed query param: ' + result);
2451
+ }
2452
+ return result.replace(/\+/g, ' ');
2453
+ }
2454
+ };
2455
+ // replace any query params in the url with the provided mask value. Tries to keep the URL as instant as possible,
2456
+ // including preserving malformed text in most cases
2457
+ const maskQueryParams = function (url, maskedParams, mask) {
2458
+ if (!url || !maskedParams || !maskedParams.length) {
2459
+ return url;
2460
+ }
2461
+ const splitHash = url.split('#');
2462
+ const withoutHash = splitHash[0] || '';
2463
+ const hash = splitHash[1];
2464
+ const splitQuery = withoutHash.split('?');
2465
+ const queryString = splitQuery[1];
2466
+ const urlWithoutQueryAndHash = splitQuery[0];
2467
+ const queryParts = (queryString || '').split('&');
2468
+ // use an array of strings rather than an object to preserve ordering and duplicates
2469
+ const paramStrings = [];
2470
+ for (let i = 0; i < queryParts.length; i++) {
2471
+ const keyValuePair = queryParts[i].split('=');
2472
+ if (!isArray(keyValuePair)) {
2473
+ continue;
2474
+ } else if (maskedParams.includes(keyValuePair[0])) {
2475
+ paramStrings.push(keyValuePair[0] + '=' + mask);
1757
2476
  } else {
1758
- this._queue.push({
1759
- fn: 'alias',
1760
- args
1761
- });
2477
+ paramStrings.push(queryParts[i]);
1762
2478
  }
2479
+ }
2480
+ let result = urlWithoutQueryAndHash;
2481
+ if (queryString != null) {
2482
+ result += '?' + paramStrings.join('&');
2483
+ }
2484
+ if (hash != null) {
2485
+ result += '#' + hash;
2486
+ }
2487
+ return result;
2488
+ };
2489
+
2490
+ /**
2491
+ * this device detection code is (at time of writing) about 3% of the size of the entire library
2492
+ * this is mostly because the identifiers user in regexes and results can't be minified away since
2493
+ * they have meaning
2494
+ *
2495
+ * so, there are some pre-uglifying choices in the code to help reduce the size
2496
+ * e.g. many repeated strings are stored as variables and then old-fashioned concatenated together
2497
+ *
2498
+ * TL;DR here be dragons
2499
+ */
2500
+ const FACEBOOK = 'Facebook';
2501
+ const MOBILE = 'Mobile';
2502
+ const IOS = 'iOS';
2503
+ const ANDROID = 'Android';
2504
+ const TABLET = 'Tablet';
2505
+ const ANDROID_TABLET = ANDROID + ' ' + TABLET;
2506
+ const IPAD = 'iPad';
2507
+ const APPLE = 'Apple';
2508
+ const APPLE_WATCH = APPLE + ' Watch';
2509
+ const SAFARI = 'Safari';
2510
+ const BLACKBERRY = 'BlackBerry';
2511
+ const SAMSUNG = 'Samsung';
2512
+ const SAMSUNG_BROWSER = SAMSUNG + 'Browser';
2513
+ const SAMSUNG_INTERNET = SAMSUNG + ' Internet';
2514
+ const CHROME = 'Chrome';
2515
+ const CHROME_OS = CHROME + ' OS';
2516
+ const CHROME_IOS = CHROME + ' ' + IOS;
2517
+ const INTERNET_EXPLORER = 'Internet Explorer';
2518
+ const INTERNET_EXPLORER_MOBILE = INTERNET_EXPLORER + ' ' + MOBILE;
2519
+ const OPERA = 'Opera';
2520
+ const OPERA_MINI = OPERA + ' Mini';
2521
+ const EDGE = 'Edge';
2522
+ const MICROSOFT_EDGE = 'Microsoft ' + EDGE;
2523
+ const FIREFOX = 'Firefox';
2524
+ const FIREFOX_IOS = FIREFOX + ' ' + IOS;
2525
+ const NINTENDO = 'Nintendo';
2526
+ const PLAYSTATION = 'PlayStation';
2527
+ const XBOX = 'Xbox';
2528
+ const ANDROID_MOBILE = ANDROID + ' ' + MOBILE;
2529
+ const MOBILE_SAFARI = MOBILE + ' ' + SAFARI;
2530
+ const WINDOWS = 'Windows';
2531
+ const WINDOWS_PHONE = WINDOWS + ' Phone';
2532
+ const NOKIA = 'Nokia';
2533
+ const OUYA = 'Ouya';
2534
+ const GENERIC = 'Generic';
2535
+ const GENERIC_MOBILE = GENERIC + ' ' + MOBILE.toLowerCase();
2536
+ const GENERIC_TABLET = GENERIC + ' ' + TABLET.toLowerCase();
2537
+ const KONQUEROR = 'Konqueror';
2538
+ const BROWSER_VERSION_REGEX_SUFFIX = '(\\d+(\\.\\d+)?)';
2539
+ const DEFAULT_BROWSER_VERSION_REGEX = new RegExp('Version/' + BROWSER_VERSION_REGEX_SUFFIX);
2540
+ const XBOX_REGEX = new RegExp(XBOX, 'i');
2541
+ const PLAYSTATION_REGEX = new RegExp(PLAYSTATION + ' \\w+', 'i');
2542
+ const NINTENDO_REGEX = new RegExp(NINTENDO + ' \\w+', 'i');
2543
+ const BLACKBERRY_REGEX = new RegExp(BLACKBERRY + '|PlayBook|BB10', 'i');
2544
+ const windowsVersionMap = {
2545
+ 'NT3.51': 'NT 3.11',
2546
+ 'NT4.0': 'NT 4.0',
2547
+ '5.0': '2000',
2548
+ '5.1': 'XP',
2549
+ '5.2': 'XP',
2550
+ '6.0': 'Vista',
2551
+ '6.1': '7',
2552
+ '6.2': '8',
2553
+ '6.3': '8.1',
2554
+ '6.4': '10',
2555
+ '10.0': '10'
2556
+ };
2557
+ /**
2558
+ * Safari detection turns out to be complicated. For e.g. https://stackoverflow.com/a/29696509
2559
+ * We can be slightly loose because some options have been ruled out (e.g. firefox on iOS)
2560
+ * before this check is made
2561
+ */
2562
+ function isSafari(userAgent) {
2563
+ return includes(userAgent, SAFARI) && !includes(userAgent, CHROME) && !includes(userAgent, ANDROID);
2564
+ }
2565
+ const safariCheck = (ua, vendor) => vendor && includes(vendor, APPLE) || isSafari(ua);
2566
+ /**
2567
+ * This function detects which browser is running this script.
2568
+ * The order of the checks are important since many user agents
2569
+ * include keywords used in later checks.
2570
+ */
2571
+ const detectBrowser = function (user_agent, vendor) {
2572
+ vendor = vendor || ''; // vendor is undefined for at least IE9
2573
+ if (includes(user_agent, ' OPR/') && includes(user_agent, 'Mini')) {
2574
+ return OPERA_MINI;
2575
+ } else if (includes(user_agent, ' OPR/')) {
2576
+ return OPERA;
2577
+ } else if (BLACKBERRY_REGEX.test(user_agent)) {
2578
+ return BLACKBERRY;
2579
+ } else if (includes(user_agent, 'IE' + MOBILE) || includes(user_agent, 'WPDesktop')) {
2580
+ return INTERNET_EXPLORER_MOBILE;
2581
+ }
2582
+ // https://developer.samsung.com/internet/user-agent-string-format
2583
+ else if (includes(user_agent, SAMSUNG_BROWSER)) {
2584
+ return SAMSUNG_INTERNET;
2585
+ } else if (includes(user_agent, EDGE) || includes(user_agent, 'Edg/')) {
2586
+ return MICROSOFT_EDGE;
2587
+ } else if (includes(user_agent, 'FBIOS')) {
2588
+ return FACEBOOK + ' ' + MOBILE;
2589
+ } else if (includes(user_agent, 'UCWEB') || includes(user_agent, 'UCBrowser')) {
2590
+ return 'UC Browser';
2591
+ } else if (includes(user_agent, 'CriOS')) {
2592
+ return CHROME_IOS; // why not just Chrome?
2593
+ } else if (includes(user_agent, 'CrMo')) {
2594
+ return CHROME;
2595
+ } else if (includes(user_agent, CHROME)) {
2596
+ return CHROME;
2597
+ } else if (includes(user_agent, ANDROID) && includes(user_agent, SAFARI)) {
2598
+ return ANDROID_MOBILE;
2599
+ } else if (includes(user_agent, 'FxiOS')) {
2600
+ return FIREFOX_IOS;
2601
+ } else if (includes(user_agent.toLowerCase(), KONQUEROR.toLowerCase())) {
2602
+ return KONQUEROR;
2603
+ } else if (safariCheck(user_agent, vendor)) {
2604
+ return includes(user_agent, MOBILE) ? MOBILE_SAFARI : SAFARI;
2605
+ } else if (includes(user_agent, FIREFOX)) {
2606
+ return FIREFOX;
2607
+ } else if (includes(user_agent, 'MSIE') || includes(user_agent, 'Trident/')) {
2608
+ return INTERNET_EXPLORER;
2609
+ } else if (includes(user_agent, 'Gecko')) {
2610
+ return FIREFOX;
2611
+ }
2612
+ return '';
2613
+ };
2614
+ const versionRegexes = {
2615
+ [INTERNET_EXPLORER_MOBILE]: [new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)],
2616
+ [MICROSOFT_EDGE]: [new RegExp(EDGE + '?\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
2617
+ [CHROME]: [new RegExp('(' + CHROME + '|CrMo)\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
2618
+ [CHROME_IOS]: [new RegExp('CriOS\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
2619
+ 'UC Browser': [new RegExp('(UCBrowser|UCWEB)\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
2620
+ [SAFARI]: [DEFAULT_BROWSER_VERSION_REGEX],
2621
+ [MOBILE_SAFARI]: [DEFAULT_BROWSER_VERSION_REGEX],
2622
+ [OPERA]: [new RegExp('(' + OPERA + '|OPR)\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
2623
+ [FIREFOX]: [new RegExp(FIREFOX + '\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
2624
+ [FIREFOX_IOS]: [new RegExp('FxiOS\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
2625
+ [KONQUEROR]: [new RegExp('Konqueror[:/]?' + BROWSER_VERSION_REGEX_SUFFIX, 'i')],
2626
+ // not every blackberry user agent has the version after the name
2627
+ [BLACKBERRY]: [new RegExp(BLACKBERRY + ' ' + BROWSER_VERSION_REGEX_SUFFIX), DEFAULT_BROWSER_VERSION_REGEX],
2628
+ [ANDROID_MOBILE]: [new RegExp('android\\s' + BROWSER_VERSION_REGEX_SUFFIX, 'i')],
2629
+ [SAMSUNG_INTERNET]: [new RegExp(SAMSUNG_BROWSER + '\\/' + BROWSER_VERSION_REGEX_SUFFIX)],
2630
+ [INTERNET_EXPLORER]: [new RegExp('(rv:|MSIE )' + BROWSER_VERSION_REGEX_SUFFIX)],
2631
+ Mozilla: [new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)]
2632
+ };
2633
+ /**
2634
+ * This function detects which browser version is running this script,
2635
+ * parsing major and minor version (e.g., 42.1). User agent strings from:
2636
+ * http://www.useragentstring.com/pages/useragentstring.php
2637
+ *
2638
+ * `navigator.vendor` is passed in and used to help with detecting certain browsers
2639
+ * NB `navigator.vendor` is deprecated and not present in every browser
2640
+ */
2641
+ const detectBrowserVersion = function (userAgent, vendor) {
2642
+ const browser = detectBrowser(userAgent, vendor);
2643
+ const regexes = versionRegexes[browser];
2644
+ if (isUndefined(regexes)) {
2645
+ return null;
2646
+ }
2647
+ for (let i = 0; i < regexes.length; i++) {
2648
+ const regex = regexes[i];
2649
+ const matches = userAgent.match(regex);
2650
+ if (matches) {
2651
+ return parseFloat(matches[matches.length - 2]);
2652
+ }
2653
+ }
2654
+ return null;
2655
+ };
2656
+ // to avoid repeating regexes or calling them twice, we have an array of matches
2657
+ // the first regex that matches uses its matcher function to return the result
2658
+ const osMatchers = [[new RegExp(XBOX + '; ' + XBOX + ' (.*?)[);]', 'i'), match => {
2659
+ return [XBOX, match && match[1] || ''];
2660
+ }], [new RegExp(NINTENDO, 'i'), [NINTENDO, '']], [new RegExp(PLAYSTATION, 'i'), [PLAYSTATION, '']], [BLACKBERRY_REGEX, [BLACKBERRY, '']], [new RegExp(WINDOWS, 'i'), (_, user_agent) => {
2661
+ if (/Phone/.test(user_agent) || /WPDesktop/.test(user_agent)) {
2662
+ return [WINDOWS_PHONE, ''];
2663
+ }
2664
+ // not all JS versions support negative lookbehind, so we need two checks here
2665
+ if (new RegExp(MOBILE).test(user_agent) && !/IEMobile\b/.test(user_agent)) {
2666
+ return [WINDOWS + ' ' + MOBILE, ''];
2667
+ }
2668
+ const match = /Windows NT ([0-9.]+)/i.exec(user_agent);
2669
+ if (match && match[1]) {
2670
+ const version = match[1];
2671
+ let osVersion = windowsVersionMap[version] || '';
2672
+ if (/arm/i.test(user_agent)) {
2673
+ osVersion = 'RT';
2674
+ }
2675
+ return [WINDOWS, osVersion];
2676
+ }
2677
+ return [WINDOWS, ''];
2678
+ }], [/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/, match => {
2679
+ if (match && match[3]) {
2680
+ const versionParts = [match[3], match[4], match[5] || '0'];
2681
+ return [IOS, versionParts.join('.')];
2682
+ }
2683
+ return [IOS, ''];
2684
+ }], [/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i, match => {
2685
+ // e.g. Watch4,3/5.3.8 (16U680)
2686
+ let version = '';
2687
+ if (match && match.length >= 3) {
2688
+ version = isUndefined(match[2]) ? match[3] : match[2];
2689
+ }
2690
+ return ['watchOS', version];
2691
+ }], [new RegExp('(' + ANDROID + ' (\\d+)\\.(\\d+)\\.?(\\d+)?|' + ANDROID + ')', 'i'), match => {
2692
+ if (match && match[2]) {
2693
+ const versionParts = [match[2], match[3], match[4] || '0'];
2694
+ return [ANDROID, versionParts.join('.')];
2695
+ }
2696
+ return [ANDROID, ''];
2697
+ }], [/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i, match => {
2698
+ const result = ['Mac OS X', ''];
2699
+ if (match && match[1]) {
2700
+ const versionParts = [match[1], match[2], match[3] || '0'];
2701
+ result[1] = versionParts.join('.');
2702
+ }
2703
+ return result;
2704
+ }], [/Mac/i,
2705
+ // mop up a few non-standard UAs that should match mac
2706
+ ['Mac OS X', '']], [/CrOS/, [CHROME_OS, '']], [/Linux|debian/i, ['Linux', '']]];
2707
+ const detectOS = function (user_agent) {
2708
+ for (let i = 0; i < osMatchers.length; i++) {
2709
+ const [rgex, resultOrFn] = osMatchers[i];
2710
+ const match = rgex.exec(user_agent);
2711
+ const result = match && (isFunction(resultOrFn) ? resultOrFn(match, user_agent) : resultOrFn);
2712
+ if (result) {
2713
+ return result;
2714
+ }
2715
+ }
2716
+ return ['', ''];
2717
+ };
2718
+ const detectDevice = function (user_agent) {
2719
+ if (NINTENDO_REGEX.test(user_agent)) {
2720
+ return NINTENDO;
2721
+ } else if (PLAYSTATION_REGEX.test(user_agent)) {
2722
+ return PLAYSTATION;
2723
+ } else if (XBOX_REGEX.test(user_agent)) {
2724
+ return XBOX;
2725
+ } else if (new RegExp(OUYA, 'i').test(user_agent)) {
2726
+ return OUYA;
2727
+ } else if (new RegExp('(' + WINDOWS_PHONE + '|WPDesktop)', 'i').test(user_agent)) {
2728
+ return WINDOWS_PHONE;
2729
+ } else if (/iPad/.test(user_agent)) {
2730
+ return IPAD;
2731
+ } else if (/iPod/.test(user_agent)) {
2732
+ return 'iPod Touch';
2733
+ } else if (/iPhone/.test(user_agent)) {
2734
+ return 'iPhone';
2735
+ } else if (/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(user_agent)) {
2736
+ return APPLE_WATCH;
2737
+ } else if (BLACKBERRY_REGEX.test(user_agent)) {
2738
+ return BLACKBERRY;
2739
+ } else if (/(kobo)\s(ereader|touch)/i.test(user_agent)) {
2740
+ return 'Kobo';
2741
+ } else if (new RegExp(NOKIA, 'i').test(user_agent)) {
2742
+ return NOKIA;
2743
+ } else if (
2744
+ // Kindle Fire without Silk / Echo Show
2745
+ /(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(user_agent) ||
2746
+ // Kindle Fire HD
2747
+ /(kf[a-z]+)( bui|\)).+silk\//i.test(user_agent)) {
2748
+ return 'Kindle Fire';
2749
+ } else if (/(Android|ZTE)/i.test(user_agent)) {
2750
+ if (!new RegExp(MOBILE).test(user_agent) || /(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(user_agent)) {
2751
+ 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)) {
2752
+ return ANDROID;
2753
+ }
2754
+ return ANDROID_TABLET;
2755
+ } else {
2756
+ return ANDROID;
2757
+ }
2758
+ } else if (new RegExp('(pda|' + MOBILE + ')', 'i').test(user_agent)) {
2759
+ return GENERIC_MOBILE;
2760
+ } else if (new RegExp(TABLET, 'i').test(user_agent) && !new RegExp(TABLET + ' pc', 'i').test(user_agent)) {
2761
+ return GENERIC_TABLET;
2762
+ } else {
2763
+ return '';
2764
+ }
2765
+ };
2766
+ const detectDeviceType = function (user_agent) {
2767
+ const device = detectDevice(user_agent);
2768
+ if (device === IPAD || device === ANDROID_TABLET || device === 'Kobo' || device === 'Kindle Fire' || device === GENERIC_TABLET) {
2769
+ return TABLET;
2770
+ } else if (device === NINTENDO || device === XBOX || device === PLAYSTATION || device === OUYA) {
2771
+ return 'Console';
2772
+ } else if (device === APPLE_WATCH) {
2773
+ return 'Wearable';
2774
+ } else if (device) {
2775
+ return MOBILE;
2776
+ } else {
2777
+ return 'Desktop';
2778
+ }
2779
+ };
2780
+
2781
+ var version = "0.1.3";
2782
+ var packageInfo = {
2783
+ version: version};
2784
+
2785
+ const Config = {
2786
+ LIB_VERSION: packageInfo.version
2787
+ };
2788
+
2789
+ const URL_REGEX_PREFIX = 'https?://(.*)';
2790
+ // CAMPAIGN_PARAMS and EVENT_TO_PERSON_PROPERTIES should be kept in sync with
2791
+ // https://github.com/PostHog/posthog/blob/master/plugin-server/src/utils/db/utils.ts#L60
2792
+ // The list of campaign parameters that could be considered personal data under e.g. GDPR.
2793
+ // These can be masked in URLs and properties before being sent to posthog.
2794
+ const PERSONAL_DATA_CAMPAIGN_PARAMS = ['gclid',
2795
+ // google ads
2796
+ 'gclsrc',
2797
+ // google ads 360
2798
+ 'dclid',
2799
+ // google display ads
2800
+ 'gbraid',
2801
+ // google ads, web to app
2802
+ 'wbraid',
2803
+ // google ads, app to web
2804
+ 'fbclid',
2805
+ // facebook
2806
+ 'msclkid',
2807
+ // microsoft
2808
+ 'twclid',
2809
+ // twitter
2810
+ 'li_fat_id',
2811
+ // linkedin
2812
+ 'igshid',
2813
+ // instagram
2814
+ 'ttclid',
2815
+ // tiktok
2816
+ 'rdt_cid',
2817
+ // reddit
2818
+ 'epik',
2819
+ // pinterest
2820
+ 'qclid',
2821
+ // quora
2822
+ 'sccid',
2823
+ // snapchat
2824
+ 'irclid',
2825
+ // impact
2826
+ '_kx' // klaviyo
2827
+ ];
2828
+ const CAMPAIGN_PARAMS = extendArray(['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'gad_source',
2829
+ // google ads source
2830
+ 'mc_cid' // mailchimp campaign id
2831
+ ], PERSONAL_DATA_CAMPAIGN_PARAMS);
2832
+ const MASKED = '<masked>';
2833
+ // Campaign params that can be read from the cookie store
2834
+ const COOKIE_CAMPAIGN_PARAMS = ['li_fat_id' // linkedin
2835
+ ];
2836
+ function getCampaignParams(customTrackedParams, maskPersonalDataProperties, customPersonalDataProperties) {
2837
+ if (!document) {
2838
+ return {};
2839
+ }
2840
+ const paramsToMask = maskPersonalDataProperties ? extendArray([], PERSONAL_DATA_CAMPAIGN_PARAMS, customPersonalDataProperties || []) : [];
2841
+ // Initially get campaign params from the URL
2842
+ const urlCampaignParams = _getCampaignParamsFromUrl(maskQueryParams(document.URL, paramsToMask, MASKED), customTrackedParams);
2843
+ // But we can also get some of them from the cookie store
2844
+ // 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
2845
+ const cookieCampaignParams = _getCampaignParamsFromCookie();
2846
+ // Prefer the values found in the urlCampaignParams if possible
2847
+ // `extend` will override the values if found in the second argument
2848
+ return extend(cookieCampaignParams, urlCampaignParams);
2849
+ }
2850
+ function _getCampaignParamsFromUrl(url, customParams) {
2851
+ const campaign_keywords = CAMPAIGN_PARAMS.concat(customParams || []);
2852
+ const params = {};
2853
+ each(campaign_keywords, function (kwkey) {
2854
+ const kw = getQueryParam(url, kwkey);
2855
+ params[kwkey] = kw ? kw : null;
2856
+ });
2857
+ return params;
2858
+ }
2859
+ function _getCampaignParamsFromCookie() {
2860
+ const params = {};
2861
+ each(COOKIE_CAMPAIGN_PARAMS, function (kwkey) {
2862
+ const kw = cookieStore._get(kwkey);
2863
+ params[kwkey] = kw ? kw : null;
2864
+ });
2865
+ return params;
2866
+ }
2867
+ function _getSearchEngine(referrer) {
2868
+ if (!referrer) {
2869
+ return null;
2870
+ } else {
2871
+ if (referrer.search(URL_REGEX_PREFIX + 'google.([^/?]*)') === 0) {
2872
+ return 'google';
2873
+ } else if (referrer.search(URL_REGEX_PREFIX + 'bing.com') === 0) {
2874
+ return 'bing';
2875
+ } else if (referrer.search(URL_REGEX_PREFIX + 'yahoo.com') === 0) {
2876
+ return 'yahoo';
2877
+ } else if (referrer.search(URL_REGEX_PREFIX + 'duckduckgo.com') === 0) {
2878
+ return 'duckduckgo';
2879
+ } else {
2880
+ return null;
2881
+ }
2882
+ }
2883
+ }
2884
+ function _getSearchInfoFromReferrer(referrer) {
2885
+ const search = _getSearchEngine(referrer);
2886
+ const param = search != 'yahoo' ? 'q' : 'p';
2887
+ const ret = {};
2888
+ if (!isNull(search)) {
2889
+ ret['$search_engine'] = search;
2890
+ const keyword = document ? getQueryParam(document.referrer, param) : '';
2891
+ if (keyword.length) {
2892
+ ret['ph_keyword'] = keyword;
2893
+ }
2894
+ }
2895
+ return ret;
2896
+ }
2897
+ function getSearchInfo() {
2898
+ const referrer = document?.referrer;
2899
+ if (!referrer) {
2900
+ return {};
2901
+ }
2902
+ return _getSearchInfoFromReferrer(referrer);
2903
+ }
2904
+ function getBrowserLanguage() {
2905
+ return navigator.language ||
2906
+ // Any modern browser
2907
+ navigator.userLanguage // IE11
2908
+ ;
2909
+ }
2910
+ function getBrowserLanguagePrefix() {
2911
+ const lang = getBrowserLanguage();
2912
+ return typeof lang === 'string' ? lang.split('-')[0] : undefined;
2913
+ }
2914
+ function getReferrer() {
2915
+ return document?.referrer || '$direct';
2916
+ }
2917
+ function getReferringDomain() {
2918
+ if (!document?.referrer) {
2919
+ return '$direct';
2920
+ }
2921
+ return convertToURL(document.referrer)?.host || '$direct';
2922
+ }
2923
+ function getReferrerInfo() {
2924
+ return {
2925
+ $referrer: getReferrer(),
2926
+ $referring_domain: getReferringDomain()
2927
+ };
2928
+ }
2929
+ function getPersonInfo(maskPersonalDataProperties, customPersonalDataProperties) {
2930
+ const paramsToMask = maskPersonalDataProperties ? extendArray([], PERSONAL_DATA_CAMPAIGN_PARAMS, customPersonalDataProperties || []) : [];
2931
+ const url = location?.href.substring(0, 1000);
2932
+ // we're being a bit more economical with bytes here because this is stored in the cookie
2933
+ return {
2934
+ r: getReferrer().substring(0, 1000),
2935
+ u: url ? maskQueryParams(url, paramsToMask, MASKED) : undefined
2936
+ };
2937
+ }
2938
+ function getPersonPropsFromInfo(info) {
2939
+ const {
2940
+ r: referrer,
2941
+ u: url
2942
+ } = info;
2943
+ const referring_domain = referrer == null ? undefined : referrer == '$direct' ? '$direct' : convertToURL(referrer)?.host;
2944
+ const props = {
2945
+ $referrer: referrer,
2946
+ $referring_domain: referring_domain
2947
+ };
2948
+ if (url) {
2949
+ props['$current_url'] = url;
2950
+ const location = convertToURL(url);
2951
+ props['$host'] = location?.host;
2952
+ props['$pathname'] = location?.pathname;
2953
+ const campaignParams = _getCampaignParamsFromUrl(url);
2954
+ extend(props, campaignParams);
2955
+ }
2956
+ if (referrer) {
2957
+ const searchInfo = _getSearchInfoFromReferrer(referrer);
2958
+ extend(props, searchInfo);
2959
+ }
2960
+ return props;
2961
+ }
2962
+ function getInitialPersonPropsFromInfo(info) {
2963
+ const personProps = getPersonPropsFromInfo(info);
2964
+ const props = {};
2965
+ each(personProps, function (val, key) {
2966
+ props[`$initial_${stripLeadingDollar(key)}`] = val;
2967
+ });
2968
+ return props;
2969
+ }
2970
+ function getTimezone() {
2971
+ try {
2972
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
2973
+ } catch {
2974
+ return undefined;
2975
+ }
2976
+ }
2977
+ function getTimezoneOffset() {
2978
+ try {
2979
+ return new Date().getTimezoneOffset();
2980
+ } catch {
2981
+ return undefined;
2982
+ }
2983
+ }
2984
+ function getEventProperties(maskPersonalDataProperties, customPersonalDataProperties) {
2985
+ if (!userAgent) {
2986
+ return {};
2987
+ }
2988
+ const paramsToMask = maskPersonalDataProperties ? extendArray([], PERSONAL_DATA_CAMPAIGN_PARAMS, customPersonalDataProperties || []) : [];
2989
+ const [os_name, os_version] = detectOS(userAgent);
2990
+ return extend(stripEmptyProperties({
2991
+ $os: os_name,
2992
+ $os_version: os_version,
2993
+ $browser: detectBrowser(userAgent, navigator.vendor),
2994
+ $device: detectDevice(userAgent),
2995
+ $device_type: detectDeviceType(userAgent),
2996
+ $timezone: getTimezone(),
2997
+ $timezone_offset: getTimezoneOffset()
2998
+ }), {
2999
+ $current_url: maskQueryParams(location?.href, paramsToMask, MASKED),
3000
+ $host: location?.host,
3001
+ $pathname: location?.pathname,
3002
+ $raw_user_agent: userAgent.length > 1000 ? userAgent.substring(0, 997) + '...' : userAgent,
3003
+ $browser_version: detectBrowserVersion(userAgent, navigator.vendor),
3004
+ $browser_language: getBrowserLanguage(),
3005
+ $browser_language_prefix: getBrowserLanguagePrefix(),
3006
+ $screen_height: win?.screen.height,
3007
+ $screen_width: win?.screen.width,
3008
+ $viewport_height: win?.innerHeight,
3009
+ $viewport_width: win?.innerWidth,
3010
+ $lib: 'web',
3011
+ $lib_version: Config.LIB_VERSION,
3012
+ $insert_id: Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10),
3013
+ $time: Date.now() / 1000 // epoch time in seconds
3014
+ });
3015
+ }
3016
+
3017
+ /* eslint camelcase: "off" */
3018
+ const CASE_INSENSITIVE_PERSISTENCE_TYPES = ['cookie', 'localstorage', 'localstorage+cookie', 'sessionstorage', 'memory'];
3019
+ const parseName = config => {
3020
+ let token = '';
3021
+ if (config['token']) {
3022
+ token = config['token'].replace(/\+/g, 'PL').replace(/\//g, 'SL').replace(/=/g, 'EQ');
3023
+ }
3024
+ if (config['persistence_name']) {
3025
+ return config['persistence_name'];
3026
+ }
3027
+ return 'leanbase_' + token;
3028
+ };
3029
+ /**
3030
+ * Leanbase Persistence Object
3031
+ * @constructor
3032
+ */
3033
+ class LeanbasePersistence {
3034
+ /**
3035
+ * @param {LeanbaseConfig} config initial PostHog configuration
3036
+ * @param {boolean=} isDisabled should persistence be disabled (e.g. because of consent management)
3037
+ */
3038
+ constructor(config, isDisabled) {
3039
+ this._config = config;
3040
+ this.props = {};
3041
+ this._campaign_params_saved = false;
3042
+ this._name = parseName(config);
3043
+ this._storage = this._buildStorage(config);
3044
+ this.load();
3045
+ if (config.debug) {
3046
+ logger.info('Persistence loaded', config['persistence'], {
3047
+ ...this.props
3048
+ });
3049
+ }
3050
+ this.update_config(config, config, isDisabled);
3051
+ this.save();
3052
+ }
3053
+ /**
3054
+ * Returns whether persistence is disabled. Only available in SDKs > 1.257.1. Do not use on extensions, otherwise
3055
+ * it'll break backwards compatibility for any version before 1.257.1.
3056
+ */
3057
+ isDisabled() {
3058
+ return !!this._disabled;
3059
+ }
3060
+ _buildStorage(config) {
3061
+ if (CASE_INSENSITIVE_PERSISTENCE_TYPES.indexOf(config['persistence'].toLowerCase()) === -1) {
3062
+ logger.info('Unknown persistence type ' + config['persistence'] + '; falling back to localStorage+cookie');
3063
+ config['persistence'] = 'localStorage+cookie';
3064
+ }
3065
+ let store;
3066
+ const storage_type = config['persistence'].toLowerCase();
3067
+ if (storage_type === 'localstorage' && localStore._is_supported()) {
3068
+ store = localStore;
3069
+ } else if (storage_type === 'localstorage+cookie' && localPlusCookieStore._is_supported()) {
3070
+ store = localPlusCookieStore;
3071
+ } else if (storage_type === 'sessionstorage' && sessionStore._is_supported()) {
3072
+ store = sessionStore;
3073
+ } else if (storage_type === 'memory') {
3074
+ store = memoryStore;
3075
+ } else if (storage_type === 'cookie') {
3076
+ store = cookieStore;
3077
+ } else if (localPlusCookieStore._is_supported()) {
3078
+ store = localPlusCookieStore;
3079
+ } else {
3080
+ store = cookieStore;
3081
+ }
3082
+ return store;
3083
+ }
3084
+ properties() {
3085
+ const p = {};
3086
+ // Filter out reserved properties
3087
+ each(this.props, function (v, k) {
3088
+ if (k === ENABLED_FEATURE_FLAGS && isObject(v)) {
3089
+ const keys = Object.keys(v);
3090
+ for (let i = 0; i < keys.length; i++) {
3091
+ p[`$feature/${keys[i]}`] = v[keys[i]];
3092
+ }
3093
+ } else if (!include(PERSISTENCE_RESERVED_PROPERTIES, k)) {
3094
+ p[k] = v;
3095
+ }
3096
+ });
3097
+ return p;
3098
+ }
3099
+ load() {
3100
+ if (this._disabled) {
3101
+ return;
3102
+ }
3103
+ const entry = this._storage._parse(this._name);
3104
+ if (entry) {
3105
+ this.props = extend({}, entry);
3106
+ }
3107
+ }
3108
+ /**
3109
+ * NOTE: Saving frequently causes issues with Recordings and Consent Management Platform (CMP) tools which
3110
+ * observe cookie changes, and modify their UI, often causing infinite loops.
3111
+ * As such callers of this should ideally check that the data has changed beforehand
3112
+ */
3113
+ save() {
3114
+ if (this._disabled) {
3115
+ return;
3116
+ }
3117
+ this._storage._set(this._name, this.props, this._expire_days, this._cross_subdomain, this._secure, this._config.debug);
3118
+ }
3119
+ remove() {
3120
+ this._storage._remove(this._name, false);
3121
+ this._storage._remove(this._name, true);
3122
+ }
3123
+ clear() {
3124
+ this.remove();
3125
+ this.props = {};
3126
+ }
3127
+ /**
3128
+ * @param {Object} props
3129
+ * @param {*=} default_value
3130
+ * @param {number=} days
3131
+ */
3132
+ register_once(props, default_value, days) {
3133
+ if (isObject(props)) {
3134
+ if (isUndefined(default_value)) {
3135
+ default_value = 'None';
3136
+ }
3137
+ this._expire_days = isUndefined(days) ? this._default_expiry : days;
3138
+ let hasChanges = false;
3139
+ each(props, (val, prop) => {
3140
+ if (!this.props.hasOwnProperty(prop) || this.props[prop] === default_value) {
3141
+ this.props[prop] = val;
3142
+ hasChanges = true;
3143
+ }
3144
+ });
3145
+ if (hasChanges) {
3146
+ this.save();
3147
+ return true;
3148
+ }
3149
+ }
3150
+ return false;
3151
+ }
3152
+ /**
3153
+ * @param {Object} props
3154
+ * @param {number=} days
3155
+ */
3156
+ register(props, days) {
3157
+ if (isObject(props)) {
3158
+ this._expire_days = isUndefined(days) ? this._default_expiry : days;
3159
+ let hasChanges = false;
3160
+ each(props, (val, prop) => {
3161
+ if (props.hasOwnProperty(prop) && this.props[prop] !== val) {
3162
+ this.props[prop] = val;
3163
+ hasChanges = true;
3164
+ }
3165
+ });
3166
+ if (hasChanges) {
3167
+ this.save();
3168
+ return true;
3169
+ }
3170
+ }
3171
+ return false;
3172
+ }
3173
+ unregister(prop) {
3174
+ if (prop in this.props) {
3175
+ delete this.props[prop];
3176
+ this.save();
3177
+ }
3178
+ }
3179
+ update_campaign_params() {
3180
+ if (!this._campaign_params_saved) {
3181
+ const campaignParams = getCampaignParams(this._config.custom_campaign_params, this._config.mask_personal_data_properties, this._config.custom_personal_data_properties);
3182
+ if (!isEmptyObject(stripEmptyProperties(campaignParams))) {
3183
+ this.register(campaignParams);
3184
+ }
3185
+ this._campaign_params_saved = true;
3186
+ }
3187
+ }
3188
+ update_search_keyword() {
3189
+ this.register(getSearchInfo());
3190
+ }
3191
+ update_referrer_info() {
3192
+ this.register_once(getReferrerInfo(), undefined);
3193
+ }
3194
+ set_initial_person_info() {
3195
+ if (this.props[INITIAL_CAMPAIGN_PARAMS] || this.props[INITIAL_REFERRER_INFO]) {
3196
+ return;
3197
+ }
3198
+ this.register_once({
3199
+ [INITIAL_PERSON_INFO]: getPersonInfo(this._config.mask_personal_data_properties, this._config.custom_personal_data_properties)
3200
+ }, undefined);
3201
+ }
3202
+ get_initial_props() {
3203
+ const p = {};
3204
+ each([INITIAL_REFERRER_INFO, INITIAL_CAMPAIGN_PARAMS], key => {
3205
+ const initialReferrerInfo = this.props[key];
3206
+ if (initialReferrerInfo) {
3207
+ each(initialReferrerInfo, function (v, k) {
3208
+ p['$initial_' + stripLeadingDollar(k)] = v;
3209
+ });
3210
+ }
3211
+ });
3212
+ const initialPersonInfo = this.props[INITIAL_PERSON_INFO];
3213
+ if (initialPersonInfo) {
3214
+ const initialPersonProps = getInitialPersonPropsFromInfo(initialPersonInfo);
3215
+ extend(p, initialPersonProps);
3216
+ }
3217
+ return p;
3218
+ }
3219
+ safe_merge(props) {
3220
+ each(this.props, function (val, prop) {
3221
+ if (!(prop in props)) {
3222
+ props[prop] = val;
3223
+ }
3224
+ });
3225
+ return props;
3226
+ }
3227
+ update_config(config, oldConfig, isDisabled) {
3228
+ this._default_expiry = this._expire_days = config['cookie_expiration'];
3229
+ this.set_disabled(config['disable_persistence'] || !!isDisabled);
3230
+ this.set_cross_subdomain(config['cross_subdomain_cookie']);
3231
+ this.set_secure(config['secure_cookie']);
3232
+ if (config.persistence !== oldConfig.persistence) {
3233
+ const newStore = this._buildStorage(config);
3234
+ const props = this.props;
3235
+ this.clear();
3236
+ this._storage = newStore;
3237
+ this.props = props;
3238
+ this.save();
3239
+ }
3240
+ }
3241
+ set_disabled(disabled) {
3242
+ this._disabled = disabled;
3243
+ if (this._disabled) {
3244
+ return this.remove();
3245
+ }
3246
+ this.save();
3247
+ }
3248
+ set_cross_subdomain(cross_subdomain) {
3249
+ if (cross_subdomain !== this._cross_subdomain) {
3250
+ this._cross_subdomain = cross_subdomain;
3251
+ this.remove();
3252
+ this.save();
3253
+ }
3254
+ }
3255
+ set_secure(secure) {
3256
+ if (secure !== this._secure) {
3257
+ this._secure = secure;
3258
+ this.remove();
3259
+ this.save();
3260
+ }
3261
+ }
3262
+ set_event_timer(event_name, timestamp) {
3263
+ const timers = this.props[EVENT_TIMERS_KEY] || {};
3264
+ timers[event_name] = timestamp;
3265
+ this.props[EVENT_TIMERS_KEY] = timers;
3266
+ this.save();
3267
+ }
3268
+ remove_event_timer(event_name) {
3269
+ const timers = this.props[EVENT_TIMERS_KEY] || {};
3270
+ const timestamp = timers[event_name];
3271
+ if (!isUndefined(timestamp)) {
3272
+ delete this.props[EVENT_TIMERS_KEY][event_name];
3273
+ this.save();
3274
+ }
3275
+ return timestamp;
3276
+ }
3277
+ get_property(prop) {
3278
+ return this.props[prop];
3279
+ }
3280
+ set_property(prop, to) {
3281
+ this.props[prop] = to;
3282
+ this.save();
3283
+ }
3284
+ }
3285
+
3286
+ /*
3287
+ * Check whether an element has nodeType Node.ELEMENT_NODE
3288
+ * @param {Element} el - element to check
3289
+ * @returns {boolean} whether el is of the correct nodeType
3290
+ */
3291
+ function isElementNode(el) {
3292
+ return !!el && el.nodeType === 1; // Node.ELEMENT_NODE - use integer constant for browser portability
3293
+ }
3294
+ /*
3295
+ * Check whether an element is of a given tag type.
3296
+ * Due to potential reference discrepancies (such as the webcomponents.js polyfill),
3297
+ * we want to match tagNames instead of specific references because something like
3298
+ * element === document.body won't always work because element might not be a native
3299
+ * element.
3300
+ * @param {Element} el - element to check
3301
+ * @param {string} tag - tag name (e.g., "div")
3302
+ * @returns {boolean} whether el is of the given tag type
3303
+ */
3304
+ function isTag(el, tag) {
3305
+ return !!el && !!el.tagName && el.tagName.toLowerCase() === tag.toLowerCase();
3306
+ }
3307
+ /*
3308
+ * Check whether an element has nodeType Node.TEXT_NODE
3309
+ * @param {Element} el - element to check
3310
+ * @returns {boolean} whether el is of the correct nodeType
3311
+ */
3312
+ function isTextNode(el) {
3313
+ return !!el && el.nodeType === 3; // Node.TEXT_NODE - use integer constant for browser portability
3314
+ }
3315
+ /*
3316
+ * Check whether an element has nodeType Node.DOCUMENT_FRAGMENT_NODE
3317
+ * @param {Element} el - element to check
3318
+ * @returns {boolean} whether el is of the correct nodeType
3319
+ */
3320
+ function isDocumentFragment(el) {
3321
+ return !!el && el.nodeType === 11; // Node.DOCUMENT_FRAGMENT_NODE - use integer constant for browser portability
3322
+ }
3323
+
3324
+ function splitClassString(s) {
3325
+ return s ? trim(s).split(/\s+/) : [];
3326
+ }
3327
+ function checkForURLMatches(urlsList) {
3328
+ const url = window?.location.href;
3329
+ return !!(url && urlsList && urlsList.some(regex => url.match(regex)));
3330
+ }
3331
+ /*
3332
+ * Get the className of an element, accounting for edge cases where element.className is an object
3333
+ *
3334
+ * Because this is a string it can contain unexpected characters
3335
+ * So, this method safely splits the className and returns that array.
3336
+ */
3337
+ function getClassNames(el) {
3338
+ let className = '';
3339
+ switch (typeof el.className) {
3340
+ case 'string':
3341
+ className = el.className;
3342
+ break;
3343
+ // TODO: when is this ever used?
3344
+ case 'object':
3345
+ // handle cases where className might be SVGAnimatedString or some other type
3346
+ className = (el.className && 'baseVal' in el.className ? el.className.baseVal : null) || el.getAttribute('class') || '';
3347
+ break;
3348
+ default:
3349
+ className = '';
3350
+ }
3351
+ return splitClassString(className);
3352
+ }
3353
+ function makeSafeText(s) {
3354
+ if (isNullish(s)) {
3355
+ return null;
3356
+ }
3357
+ return trim(s)
3358
+ // scrub potentially sensitive values
3359
+ .split(/(\s+)/).filter(s => shouldCaptureValue(s)).join('')
3360
+ // normalize whitespace
3361
+ .replace(/[\r\n]/g, ' ').replace(/[ ]+/g, ' ')
3362
+ // truncate
3363
+ .substring(0, 255);
3364
+ }
3365
+ /*
3366
+ * Get the direct text content of an element, protecting against sensitive data collection.
3367
+ * Concats textContent of each of the element's text node children; this avoids potential
3368
+ * collection of sensitive data that could happen if we used element.textContent and the
3369
+ * element had sensitive child elements, since element.textContent includes child content.
3370
+ * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).
3371
+ * @param {Element} el - element to get the text of
3372
+ * @returns {string} the element's direct text content
3373
+ */
3374
+ function getSafeText(el) {
3375
+ let elText = '';
3376
+ if (shouldCaptureElement(el) && !isSensitiveElement(el) && el.childNodes && el.childNodes.length) {
3377
+ each(el.childNodes, function (child) {
3378
+ if (isTextNode(child) && child.textContent) {
3379
+ elText += makeSafeText(child.textContent) ?? '';
3380
+ }
3381
+ });
3382
+ }
3383
+ return trim(elText);
3384
+ }
3385
+ function getEventTarget(e) {
3386
+ // https://developer.mozilla.org/en-US/docs/Web/API/Event/target#Compatibility_notes
3387
+ if (isUndefined(e.target)) {
3388
+ return e.srcElement || null;
3389
+ } else {
3390
+ if (e.target?.shadowRoot) {
3391
+ return e.composedPath()[0] || null;
3392
+ }
3393
+ return e.target || null;
3394
+ }
3395
+ }
3396
+ const autocaptureCompatibleElements = ['a', 'button', 'form', 'input', 'select', 'textarea', 'label'];
3397
+ /*
3398
+ if there is no config, then all elements are allowed
3399
+ if there is a config, and there is an allow list, then only elements in the allow list are allowed
3400
+ assumes that some other code is checking this element's parents
3401
+ */
3402
+ function checkIfElementTreePassesElementAllowList(elements, autocaptureConfig) {
3403
+ const allowlist = autocaptureConfig?.element_allowlist;
3404
+ if (isUndefined(allowlist)) {
3405
+ // everything is allowed, when there is no allow list
3406
+ return true;
3407
+ }
3408
+ // check each element in the tree
3409
+ // if any of the elements are in the allow list, then the tree is allowed
3410
+ for (const el of elements) {
3411
+ if (allowlist.some(elementType => el.tagName.toLowerCase() === elementType)) {
3412
+ return true;
3413
+ }
3414
+ }
3415
+ // otherwise there is an allow list and this element tree didn't match it
3416
+ return false;
3417
+ }
3418
+ /*
3419
+ if there is no selector list (i.e. it is undefined), then any elements matches
3420
+ if there is an empty list, then no elements match
3421
+ if there is a selector list, then check it against each element provided
3422
+ */
3423
+ function checkIfElementsMatchCSSSelector(elements, selectorList) {
3424
+ if (isUndefined(selectorList)) {
3425
+ // everything is allowed, when there is no selector list
3426
+ return true;
3427
+ }
3428
+ for (const el of elements) {
3429
+ if (selectorList.some(selector => el.matches(selector))) {
3430
+ return true;
3431
+ }
3432
+ }
3433
+ return false;
3434
+ }
3435
+ function getParentElement(curEl) {
3436
+ const parentNode = curEl.parentNode;
3437
+ if (!parentNode || !isElementNode(parentNode)) return false;
3438
+ return parentNode;
3439
+ }
3440
+ // autocapture check will already filter for ph-no-capture,
3441
+ // but we include it here to protect against future changes accidentally removing that check
3442
+ const DEFAULT_RAGE_CLICK_IGNORE_LIST = ['.ph-no-rageclick', '.ph-no-capture'];
3443
+ function shouldCaptureRageclick(el, _config) {
3444
+ if (!window || cannotCheckForAutocapture(el)) {
3445
+ return false;
3446
+ }
3447
+ let selectorIgnoreList;
3448
+ if (isBoolean(_config)) {
3449
+ selectorIgnoreList = _config ? DEFAULT_RAGE_CLICK_IGNORE_LIST : false;
3450
+ } else {
3451
+ selectorIgnoreList = _config?.css_selector_ignorelist ?? DEFAULT_RAGE_CLICK_IGNORE_LIST;
3452
+ }
3453
+ if (selectorIgnoreList === false) {
3454
+ return false;
3455
+ }
3456
+ const {
3457
+ targetElementList
3458
+ } = getElementAndParentsForElement(el, false);
3459
+ // we don't capture if we match the ignore list
3460
+ return !checkIfElementsMatchCSSSelector(targetElementList, selectorIgnoreList);
3461
+ }
3462
+ const cannotCheckForAutocapture = el => {
3463
+ return !el || isTag(el, 'html') || !isElementNode(el);
3464
+ };
3465
+ const getElementAndParentsForElement = (el, captureOnAnyElement) => {
3466
+ if (!window || cannotCheckForAutocapture(el)) {
3467
+ return {
3468
+ parentIsUsefulElement: false,
3469
+ targetElementList: []
3470
+ };
3471
+ }
3472
+ let parentIsUsefulElement = false;
3473
+ const targetElementList = [el];
3474
+ let curEl = el;
3475
+ while (curEl.parentNode && !isTag(curEl, 'body')) {
3476
+ // If element is a shadow root, we skip it
3477
+ if (isDocumentFragment(curEl.parentNode)) {
3478
+ targetElementList.push(curEl.parentNode.host);
3479
+ curEl = curEl.parentNode.host;
3480
+ continue;
3481
+ }
3482
+ const parentNode = getParentElement(curEl);
3483
+ if (!parentNode) break;
3484
+ if (captureOnAnyElement || autocaptureCompatibleElements.indexOf(parentNode.tagName.toLowerCase()) > -1) {
3485
+ parentIsUsefulElement = true;
3486
+ } else {
3487
+ const compStyles = window.getComputedStyle(parentNode);
3488
+ if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer') {
3489
+ parentIsUsefulElement = true;
3490
+ }
3491
+ }
3492
+ targetElementList.push(parentNode);
3493
+ curEl = parentNode;
3494
+ }
3495
+ return {
3496
+ parentIsUsefulElement,
3497
+ targetElementList
3498
+ };
3499
+ };
3500
+ /*
3501
+ * Check whether a DOM event should be "captured" or if it may contain sensitive data
3502
+ * using a variety of heuristics.
3503
+ * @param {Element} el - element to check
3504
+ * @param {Event} event - event to check
3505
+ * @param {Object} autocaptureConfig - autocapture config
3506
+ * @param {boolean} captureOnAnyElement - whether to capture on any element, clipboard autocapture doesn't restrict to "clickable" elements
3507
+ * @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")
3508
+ * @returns {boolean} whether the event should be captured
3509
+ */
3510
+ function shouldCaptureDomEvent(el, event, autocaptureConfig = undefined, captureOnAnyElement, allowedEventTypes) {
3511
+ if (!window || cannotCheckForAutocapture(el)) {
3512
+ return false;
3513
+ }
3514
+ if (autocaptureConfig?.url_allowlist) {
3515
+ // if the current URL is not in the allow list, don't capture
3516
+ if (!checkForURLMatches(autocaptureConfig.url_allowlist)) {
3517
+ return false;
3518
+ }
3519
+ }
3520
+ if (autocaptureConfig?.url_ignorelist) {
3521
+ // if the current URL is in the ignore list, don't capture
3522
+ if (checkForURLMatches(autocaptureConfig.url_ignorelist)) {
3523
+ return false;
3524
+ }
3525
+ }
3526
+ if (autocaptureConfig?.dom_event_allowlist) {
3527
+ const allowlist = autocaptureConfig.dom_event_allowlist;
3528
+ if (allowlist && !allowlist.some(eventType => event.type === eventType)) {
3529
+ return false;
3530
+ }
3531
+ }
3532
+ const {
3533
+ parentIsUsefulElement,
3534
+ targetElementList
3535
+ } = getElementAndParentsForElement(el, captureOnAnyElement);
3536
+ if (!checkIfElementTreePassesElementAllowList(targetElementList, autocaptureConfig)) {
3537
+ return false;
3538
+ }
3539
+ if (!checkIfElementsMatchCSSSelector(targetElementList, autocaptureConfig?.css_selector_allowlist)) {
3540
+ return false;
3541
+ }
3542
+ const compStyles = window.getComputedStyle(el);
3543
+ if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer' && event.type === 'click') {
3544
+ return true;
3545
+ }
3546
+ const tag = el.tagName.toLowerCase();
3547
+ switch (tag) {
3548
+ case 'html':
3549
+ return false;
3550
+ case 'form':
3551
+ return (allowedEventTypes || ['submit']).indexOf(event.type) >= 0;
3552
+ case 'input':
3553
+ case 'select':
3554
+ case 'textarea':
3555
+ return (allowedEventTypes || ['change', 'click']).indexOf(event.type) >= 0;
3556
+ default:
3557
+ if (parentIsUsefulElement) return (allowedEventTypes || ['click']).indexOf(event.type) >= 0;
3558
+ return (allowedEventTypes || ['click']).indexOf(event.type) >= 0 && (autocaptureCompatibleElements.indexOf(tag) > -1 || el.getAttribute('contenteditable') === 'true');
3559
+ }
3560
+ }
3561
+ /*
3562
+ * Check whether a DOM element should be "captured" or if it may contain sensitive data
3563
+ * using a variety of heuristics.
3564
+ * @param {Element} el - element to check
3565
+ * @returns {boolean} whether the element should be captured
3566
+ */
3567
+ function shouldCaptureElement(el) {
3568
+ for (let curEl = el; curEl.parentNode && !isTag(curEl, 'body'); curEl = curEl.parentNode) {
3569
+ const classes = getClassNames(curEl);
3570
+ if (includes(classes, 'ph-sensitive') || includes(classes, 'ph-no-capture')) {
3571
+ return false;
3572
+ }
3573
+ }
3574
+ if (includes(getClassNames(el), 'ph-include')) {
3575
+ return true;
3576
+ }
3577
+ // don't include hidden or password fields
3578
+ const type = el.type || '';
3579
+ if (isString(type)) {
3580
+ // it's possible for el.type to be a DOM element if el is a form with a child input[name="type"]
3581
+ switch (type.toLowerCase()) {
3582
+ case 'hidden':
3583
+ return false;
3584
+ case 'password':
3585
+ return false;
3586
+ }
3587
+ }
3588
+ // filter out data from fields that look like sensitive fields
3589
+ const name = el.name || el.id || '';
3590
+ // See https://github.com/posthog/posthog-js/issues/165
3591
+ // Under specific circumstances a bug caused .replace to be called on a DOM element
3592
+ // instead of a string, removing the element from the page. Ensure this issue is mitigated.
3593
+ if (isString(name)) {
3594
+ // 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"]
3595
+ const sensitiveNameRegex = /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i;
3596
+ if (sensitiveNameRegex.test(name.replace(/[^a-zA-Z0-9]/g, ''))) {
3597
+ return false;
3598
+ }
3599
+ }
3600
+ return true;
3601
+ }
3602
+ /*
3603
+ * Check whether a DOM element is 'sensitive' and we should only capture limited data
3604
+ * @param {Element} el - element to check
3605
+ * @returns {boolean} whether the element should be captured
3606
+ */
3607
+ function isSensitiveElement(el) {
3608
+ // don't send data from inputs or similar elements since there will always be
3609
+ // a risk of clientside javascript placing sensitive data in attributes
3610
+ const allowedInputTypes = ['button', 'checkbox', 'submit', 'reset'];
3611
+ if (isTag(el, 'input') && !allowedInputTypes.includes(el.type) || isTag(el, 'select') || isTag(el, 'textarea') || el.getAttribute('contenteditable') === 'true') {
3612
+ return true;
3613
+ }
3614
+ return false;
3615
+ }
3616
+ // Define the core pattern for matching credit card numbers
3617
+ 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})`;
3618
+ // Create the Anchored version of the regex by adding '^' at the start and '$' at the end
3619
+ const anchoredCCRegex = new RegExp(`^(?:${coreCCPattern})$`);
3620
+ // The Unanchored version is essentially the core pattern, usable as is for partial matches
3621
+ const unanchoredCCRegex = new RegExp(coreCCPattern);
3622
+ // Define the core pattern for matching SSNs with optional dashes
3623
+ const coreSSNPattern = `\\d{3}-?\\d{2}-?\\d{4}`;
3624
+ // Create the Anchored version of the regex by adding '^' at the start and '$' at the end
3625
+ const anchoredSSNRegex = new RegExp(`^(${coreSSNPattern})$`);
3626
+ // The Unanchored version is essentially the core pattern itself, usable for partial matches
3627
+ const unanchoredSSNRegex = new RegExp(`(${coreSSNPattern})`);
3628
+ /*
3629
+ * Check whether a string value should be "captured" or if it may contain sensitive data
3630
+ * using a variety of heuristics.
3631
+ * @param {string} value - string value to check
3632
+ * @param {boolean} anchorRegexes - whether to anchor the regexes to the start and end of the string
3633
+ * @returns {boolean} whether the element should be captured
3634
+ */
3635
+ function shouldCaptureValue(value, anchorRegexes = true) {
3636
+ if (isNullish(value)) {
3637
+ return false;
3638
+ }
3639
+ if (isString(value)) {
3640
+ value = trim(value);
3641
+ // check to see if input value looks like a credit card number
3642
+ // see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html
3643
+ const ccRegex = anchorRegexes ? anchoredCCRegex : unanchoredCCRegex;
3644
+ if (ccRegex.test((value || '').replace(/[- ]/g, ''))) {
3645
+ return false;
3646
+ }
3647
+ // check to see if input value looks like a social security number
3648
+ const ssnRegex = anchorRegexes ? anchoredSSNRegex : unanchoredSSNRegex;
3649
+ if (ssnRegex.test(value)) {
3650
+ return false;
3651
+ }
3652
+ }
3653
+ return true;
3654
+ }
3655
+ /*
3656
+ * Check whether an attribute name is an Angular style attr (either _ngcontent or _nghost)
3657
+ * These update on each build and lead to noise in the element chain
3658
+ * More details on the attributes here: https://angular.io/guide/view-encapsulation
3659
+ * @param {string} attributeName - string value to check
3660
+ * @returns {boolean} whether the element is an angular tag
3661
+ */
3662
+ function isAngularStyleAttr(attributeName) {
3663
+ if (isString(attributeName)) {
3664
+ return attributeName.substring(0, 10) === '_ngcontent' || attributeName.substring(0, 7) === '_nghost';
3665
+ }
3666
+ return false;
3667
+ }
3668
+ /*
3669
+ * Iterate through children of a target element looking for span tags
3670
+ * and return the text content of the span tags, separated by spaces,
3671
+ * along with the direct text content of the target element
3672
+ * @param {Element} target - element to check
3673
+ * @returns {string} text content of the target element and its child span tags
3674
+ */
3675
+ function getDirectAndNestedSpanText(target) {
3676
+ let text = getSafeText(target);
3677
+ text = `${text} ${getNestedSpanText(target)}`.trim();
3678
+ return shouldCaptureValue(text) ? text : '';
3679
+ }
3680
+ /*
3681
+ * Iterate through children of a target element looking for span tags
3682
+ * and return the text content of the span tags, separated by spaces
3683
+ * @param {Element} target - element to check
3684
+ * @returns {string} text content of span tags
3685
+ */
3686
+ function getNestedSpanText(target) {
3687
+ let text = '';
3688
+ if (target && target.childNodes && target.childNodes.length) {
3689
+ each(target.childNodes, function (child) {
3690
+ if (child && child.tagName?.toLowerCase() === 'span') {
3691
+ try {
3692
+ const spanText = getSafeText(child);
3693
+ text = `${text} ${spanText}`.trim();
3694
+ if (child.childNodes && child.childNodes.length) {
3695
+ text = `${text} ${getNestedSpanText(child)}`.trim();
3696
+ }
3697
+ } catch (e) {
3698
+ logger.error('[AutoCapture]', e);
3699
+ }
3700
+ }
3701
+ });
3702
+ }
3703
+ return text;
3704
+ }
3705
+ /*
3706
+ Back in the day storing events in Postgres we use Elements for autocapture events.
3707
+ Now we're using elements_chain. We used to do this parsing/processing during ingestion.
3708
+ This code is just copied over from ingestion, but we should optimize it
3709
+ to create elements_chain string directly.
3710
+ */
3711
+ function getElementsChainString(elements) {
3712
+ return elementsToString(extractElements(elements));
3713
+ }
3714
+ function escapeQuotes(input) {
3715
+ return input.replace(/"|\\"/g, '\\"');
3716
+ }
3717
+ function elementsToString(elements) {
3718
+ const ret = elements.map(element => {
3719
+ let el_string = '';
3720
+ if (element.tag_name) {
3721
+ el_string += element.tag_name;
3722
+ }
3723
+ if (element.attr_class) {
3724
+ element.attr_class.sort();
3725
+ for (const single_class of element.attr_class) {
3726
+ el_string += `.${single_class.replace(/"/g, '')}`;
3727
+ }
3728
+ }
3729
+ const attributes = {
3730
+ ...(element.text ? {
3731
+ text: element.text
3732
+ } : {}),
3733
+ 'nth-child': element.nth_child ?? 0,
3734
+ 'nth-of-type': element.nth_of_type ?? 0,
3735
+ ...(element.href ? {
3736
+ href: element.href
3737
+ } : {}),
3738
+ ...(element.attr_id ? {
3739
+ attr_id: element.attr_id
3740
+ } : {}),
3741
+ ...element.attributes
3742
+ };
3743
+ const sortedAttributes = {};
3744
+ entries(attributes).sort(([a], [b]) => a.localeCompare(b)).forEach(([key, value]) => sortedAttributes[escapeQuotes(key.toString())] = escapeQuotes(value.toString()));
3745
+ el_string += ':';
3746
+ el_string += entries(sortedAttributes).map(([key, value]) => `${key}="${value}"`).join('');
3747
+ return el_string;
3748
+ });
3749
+ return ret.join(';');
3750
+ }
3751
+ function extractElements(elements) {
3752
+ return elements.map(el => {
3753
+ const response = {
3754
+ text: el['$el_text']?.slice(0, 400),
3755
+ tag_name: el['tag_name'],
3756
+ href: el['attr__href']?.slice(0, 2048),
3757
+ attr_class: extractAttrClass(el),
3758
+ attr_id: el['attr__id'],
3759
+ nth_child: el['nth_child'],
3760
+ nth_of_type: el['nth_of_type'],
3761
+ attributes: {}
3762
+ };
3763
+ entries(el).filter(([key]) => key.indexOf('attr__') === 0).forEach(([key, value]) => response.attributes[key] = value);
3764
+ return response;
3765
+ });
3766
+ }
3767
+ function extractAttrClass(el) {
3768
+ const attr_class = el['attr__class'];
3769
+ if (!attr_class) {
3770
+ return undefined;
3771
+ } else if (isArray(attr_class)) {
3772
+ return attr_class;
3773
+ } else {
3774
+ return splitClassString(attr_class);
3775
+ }
3776
+ }
3777
+
3778
+ // Naive rage click implementation: If mouse has not moved further than RAGE_CLICK_THRESHOLD_PX
3779
+ // over RAGE_CLICK_CLICK_COUNT clicks with max RAGE_CLICK_TIMEOUT_MS between clicks, it's
3780
+ // counted as a rage click
3781
+ const RAGE_CLICK_THRESHOLD_PX = 30;
3782
+ const RAGE_CLICK_TIMEOUT_MS = 1000;
3783
+ const RAGE_CLICK_CLICK_COUNT = 3;
3784
+ class RageClick {
3785
+ constructor() {
3786
+ this.clicks = [];
3787
+ }
3788
+ isRageClick(x, y, timestamp) {
3789
+ const lastClick = this.clicks[this.clicks.length - 1];
3790
+ if (lastClick && Math.abs(x - lastClick.x) + Math.abs(y - lastClick.y) < RAGE_CLICK_THRESHOLD_PX && timestamp - lastClick.timestamp < RAGE_CLICK_TIMEOUT_MS) {
3791
+ this.clicks.push({
3792
+ x,
3793
+ y,
3794
+ timestamp
3795
+ });
3796
+ if (this.clicks.length === RAGE_CLICK_CLICK_COUNT) {
3797
+ return true;
3798
+ }
3799
+ } else {
3800
+ this.clicks = [{
3801
+ x,
3802
+ y,
3803
+ timestamp
3804
+ }];
3805
+ }
3806
+ return false;
3807
+ }
3808
+ }
3809
+
3810
+ const COPY_AUTOCAPTURE_EVENT = '$copy_autocapture';
3811
+ var Compression;
3812
+ (function (Compression) {
3813
+ Compression["GZipJS"] = "gzip-js";
3814
+ Compression["Base64"] = "base64";
3815
+ })(Compression || (Compression = {}));
3816
+
3817
+ function limitText(length, text) {
3818
+ if (text.length > length) {
3819
+ return text.slice(0, length) + '...';
3820
+ }
3821
+ return text;
3822
+ }
3823
+ function getAugmentPropertiesFromElement(elem) {
3824
+ const shouldCaptureEl = shouldCaptureElement(elem);
3825
+ if (!shouldCaptureEl) {
3826
+ return {};
3827
+ }
3828
+ const props = {};
3829
+ each(elem.attributes, function (attr) {
3830
+ if (attr.name && attr.name.indexOf('data-ph-capture-attribute') === 0) {
3831
+ const propertyKey = attr.name.replace('data-ph-capture-attribute-', '');
3832
+ const propertyValue = attr.value;
3833
+ if (propertyKey && propertyValue && shouldCaptureValue(propertyValue)) {
3834
+ props[propertyKey] = propertyValue;
3835
+ }
3836
+ }
3837
+ });
3838
+ return props;
3839
+ }
3840
+ function previousElementSibling(el) {
3841
+ if (el.previousElementSibling) {
3842
+ return el.previousElementSibling;
3843
+ }
3844
+ let _el = el;
3845
+ do {
3846
+ _el = _el.previousSibling; // resolves to ChildNode->Node, which is Element's parent class
3847
+ } while (_el && !isElementNode(_el));
3848
+ return _el;
3849
+ }
3850
+ function getDefaultProperties(eventType) {
3851
+ return {
3852
+ $event_type: eventType,
3853
+ $ce_version: 1
3854
+ };
3855
+ }
3856
+ function getPropertiesFromElement(elem, maskAllAttributes, maskText, elementAttributeIgnorelist) {
3857
+ const tag_name = elem.tagName.toLowerCase();
3858
+ const props = {
3859
+ tag_name: tag_name
3860
+ };
3861
+ if (autocaptureCompatibleElements.indexOf(tag_name) > -1 && !maskText) {
3862
+ if (tag_name.toLowerCase() === 'a' || tag_name.toLowerCase() === 'button') {
3863
+ props['$el_text'] = limitText(1024, getDirectAndNestedSpanText(elem));
3864
+ } else {
3865
+ props['$el_text'] = limitText(1024, getSafeText(elem));
3866
+ }
3867
+ }
3868
+ const classes = getClassNames(elem);
3869
+ if (classes.length > 0) props['classes'] = classes.filter(function (c) {
3870
+ return c !== '';
3871
+ });
3872
+ // capture the deny list here because this not-a-class class makes it tricky to use this.config in the function below
3873
+ each(elem.attributes, function (attr) {
3874
+ // Only capture attributes we know are safe
3875
+ if (isSensitiveElement(elem) && ['name', 'id', 'class', 'aria-label'].indexOf(attr.name) === -1) return;
3876
+ if (elementAttributeIgnorelist?.includes(attr.name)) return;
3877
+ if (!maskAllAttributes && shouldCaptureValue(attr.value) && !isAngularStyleAttr(attr.name)) {
3878
+ let value = attr.value;
3879
+ if (attr.name === 'class') {
3880
+ // html attributes can _technically_ contain linebreaks,
3881
+ // but we're very intolerant of them in the class string,
3882
+ // so we strip them.
3883
+ value = splitClassString(value).join(' ');
3884
+ }
3885
+ props['attr__' + attr.name] = limitText(1024, value);
3886
+ }
3887
+ });
3888
+ let nthChild = 1;
3889
+ let nthOfType = 1;
3890
+ let currentElem = elem;
3891
+ while (currentElem = previousElementSibling(currentElem)) {
3892
+ // eslint-disable-line no-cond-assign
3893
+ nthChild++;
3894
+ if (currentElem.tagName === elem.tagName) {
3895
+ nthOfType++;
3896
+ }
3897
+ }
3898
+ props['nth_child'] = nthChild;
3899
+ props['nth_of_type'] = nthOfType;
3900
+ return props;
3901
+ }
3902
+ function autocapturePropertiesForElement(target, {
3903
+ e,
3904
+ maskAllElementAttributes,
3905
+ maskAllText,
3906
+ elementAttributeIgnoreList,
3907
+ elementsChainAsString
3908
+ }) {
3909
+ const targetElementList = [target];
3910
+ let curEl = target;
3911
+ while (curEl.parentNode && !isTag(curEl, 'body')) {
3912
+ if (isDocumentFragment(curEl.parentNode)) {
3913
+ targetElementList.push(curEl.parentNode.host);
3914
+ curEl = curEl.parentNode.host;
3915
+ continue;
3916
+ }
3917
+ targetElementList.push(curEl.parentNode);
3918
+ curEl = curEl.parentNode;
3919
+ }
3920
+ const elementsJson = [];
3921
+ const autocaptureAugmentProperties = {};
3922
+ let href = false;
3923
+ let explicitNoCapture = false;
3924
+ each(targetElementList, el => {
3925
+ const shouldCaptureEl = shouldCaptureElement(el);
3926
+ // if the element or a parent element is an anchor tag
3927
+ // include the href as a property
3928
+ if (el.tagName.toLowerCase() === 'a') {
3929
+ href = el.getAttribute('href');
3930
+ href = shouldCaptureEl && href && shouldCaptureValue(href) && href;
3931
+ }
3932
+ // allow users to programmatically prevent capturing of elements by adding class 'ph-no-capture'
3933
+ const classes = getClassNames(el);
3934
+ if (includes(classes, 'ph-no-capture')) {
3935
+ explicitNoCapture = true;
3936
+ }
3937
+ elementsJson.push(getPropertiesFromElement(el, maskAllElementAttributes, maskAllText, elementAttributeIgnoreList));
3938
+ const augmentProperties = getAugmentPropertiesFromElement(el);
3939
+ extend(autocaptureAugmentProperties, augmentProperties);
3940
+ });
3941
+ if (explicitNoCapture) {
3942
+ return {
3943
+ props: {},
3944
+ explicitNoCapture
3945
+ };
3946
+ }
3947
+ if (!maskAllText) {
3948
+ // if the element is a button or anchor tag get the span text from any
3949
+ // children and include it as/with the text property on the parent element
3950
+ if (target.tagName.toLowerCase() === 'a' || target.tagName.toLowerCase() === 'button') {
3951
+ elementsJson[0]['$el_text'] = getDirectAndNestedSpanText(target);
3952
+ } else {
3953
+ elementsJson[0]['$el_text'] = getSafeText(target);
3954
+ }
3955
+ }
3956
+ let externalHref;
3957
+ if (href) {
3958
+ elementsJson[0]['attr__href'] = href;
3959
+ const hrefHost = convertToURL(href)?.host;
3960
+ const locationHost = win?.location?.host;
3961
+ if (hrefHost && locationHost && hrefHost !== locationHost) {
3962
+ externalHref = href;
3963
+ }
3964
+ }
3965
+ const props = extend(getDefaultProperties(e.type),
3966
+ // Sending "$elements" is deprecated. Only one client on US cloud uses this.
3967
+ !elementsChainAsString ? {
3968
+ $elements: elementsJson
3969
+ } : {},
3970
+ // Always send $elements_chain, as it's needed downstream in site app filtering
3971
+ {
3972
+ $elements_chain: getElementsChainString(elementsJson)
3973
+ }, elementsJson[0]?.['$el_text'] ? {
3974
+ $el_text: elementsJson[0]?.['$el_text']
3975
+ } : {}, externalHref && e.type === 'click' ? {
3976
+ $external_click_url: externalHref
3977
+ } : {}, autocaptureAugmentProperties);
3978
+ return {
3979
+ props
3980
+ };
3981
+ }
3982
+ class Autocapture {
3983
+ constructor(instance) {
3984
+ this._initialized = false;
3985
+ this._isDisabledServerSide = null;
3986
+ this.rageclicks = new RageClick();
3987
+ this._elementsChainAsString = false;
3988
+ this.instance = instance;
3989
+ this._elementSelectors = null;
3990
+ }
3991
+ get _config() {
3992
+ const config = isObject(this.instance.config.autocapture) ? this.instance.config.autocapture : {};
3993
+ // precompile the regex
3994
+ config.url_allowlist = config.url_allowlist?.map(url => new RegExp(url));
3995
+ config.url_ignorelist = config.url_ignorelist?.map(url => new RegExp(url));
3996
+ return config;
3997
+ }
3998
+ _addDomEventHandlers() {
3999
+ if (!this.isBrowserSupported()) {
4000
+ logger.info('Disabling Automatic Event Collection because this browser is not supported');
4001
+ return;
4002
+ }
4003
+ if (!win || !document) {
4004
+ return;
4005
+ }
4006
+ const handler = e => {
4007
+ e = e || win?.event;
4008
+ try {
4009
+ this._captureEvent(e);
4010
+ } catch (error) {
4011
+ logger.error('Failed to capture event', error);
4012
+ }
4013
+ };
4014
+ addEventListener(document, 'submit', handler, {
4015
+ capture: true
4016
+ });
4017
+ addEventListener(document, 'change', handler, {
4018
+ capture: true
4019
+ });
4020
+ addEventListener(document, 'click', handler, {
4021
+ capture: true
4022
+ });
4023
+ if (this._config.capture_copied_text) {
4024
+ const copiedTextHandler = e => {
4025
+ e = e || win?.event;
4026
+ this._captureEvent(e, COPY_AUTOCAPTURE_EVENT);
4027
+ };
4028
+ addEventListener(document, 'copy', copiedTextHandler, {
4029
+ capture: true
4030
+ });
4031
+ addEventListener(document, 'cut', copiedTextHandler, {
4032
+ capture: true
4033
+ });
4034
+ }
4035
+ }
4036
+ startIfEnabled() {
4037
+ if (this.isEnabled && !this._initialized) {
4038
+ this._addDomEventHandlers();
4039
+ this._initialized = true;
4040
+ }
4041
+ }
4042
+ onRemoteConfig(response) {
4043
+ if (response.elementsChainAsString) {
4044
+ this._elementsChainAsString = response.elementsChainAsString;
4045
+ }
4046
+ if (this.instance.persistence) {
4047
+ this.instance.persistence.register({
4048
+ [AUTOCAPTURE_DISABLED_SERVER_SIDE]: !!response['autocapture_opt_out']
4049
+ });
4050
+ }
4051
+ this._isDisabledServerSide = !!response['autocapture_opt_out'];
4052
+ this.startIfEnabled();
4053
+ }
4054
+ setElementSelectors(selectors) {
4055
+ this._elementSelectors = selectors;
4056
+ }
4057
+ getElementSelectors(element) {
4058
+ const elementSelectors = [];
4059
+ this._elementSelectors?.forEach(selector => {
4060
+ const matchedElements = document?.querySelectorAll(selector);
4061
+ matchedElements?.forEach(matchedElement => {
4062
+ if (element === matchedElement) {
4063
+ elementSelectors.push(selector);
4064
+ }
4065
+ });
4066
+ });
4067
+ return elementSelectors;
4068
+ }
4069
+ get isEnabled() {
4070
+ const persistedServerDisabled = this.instance.persistence?.props[AUTOCAPTURE_DISABLED_SERVER_SIDE];
4071
+ const memoryDisabled = this._isDisabledServerSide;
4072
+ if (isNull(memoryDisabled) && !isBoolean(persistedServerDisabled)) {
4073
+ return false;
4074
+ }
4075
+ const disabledServer = this._isDisabledServerSide ?? !!persistedServerDisabled;
4076
+ const disabledClient = !this.instance.config.autocapture;
4077
+ return !disabledClient && !disabledServer;
4078
+ }
4079
+ _captureEvent(e, eventName = '$autocapture') {
4080
+ if (!this.isEnabled) {
4081
+ return;
4082
+ }
4083
+ /*** Don't mess with this code without running IE8 tests on it ***/
4084
+ let target = getEventTarget(e);
4085
+ if (isTextNode(target)) {
4086
+ // defeat Safari bug (see: http://www.quirksmode.org/js/events_properties.html)
4087
+ target = target.parentNode || null;
4088
+ }
4089
+ if (eventName === '$autocapture' && e.type === 'click' && e instanceof MouseEvent) {
4090
+ if (!!this.instance.config.rageclick && this.rageclicks?.isRageClick(e.clientX, e.clientY, new Date().getTime())) {
4091
+ if (shouldCaptureRageclick(target, this.instance.config.rageclick)) {
4092
+ this._captureEvent(e, '$rageclick');
4093
+ }
4094
+ }
4095
+ }
4096
+ const isCopyAutocapture = eventName === COPY_AUTOCAPTURE_EVENT;
4097
+ if (target && shouldCaptureDomEvent(target, e, this._config,
4098
+ // mostly this method cares about the target element, but in the case of copy events,
4099
+ // we want some of the work this check does without insisting on the target element's type
4100
+ isCopyAutocapture,
4101
+ // we also don't want to restrict copy checks to clicks,
4102
+ // so we pass that knowledge in here, rather than add the logic inside the check
4103
+ isCopyAutocapture ? ['copy', 'cut'] : undefined)) {
4104
+ const {
4105
+ props,
4106
+ explicitNoCapture
4107
+ } = autocapturePropertiesForElement(target, {
4108
+ e,
4109
+ maskAllElementAttributes: this.instance.config.mask_all_element_attributes,
4110
+ maskAllText: this.instance.config.mask_all_text,
4111
+ elementAttributeIgnoreList: this._config.element_attribute_ignorelist,
4112
+ elementsChainAsString: this._elementsChainAsString
4113
+ });
4114
+ if (explicitNoCapture) {
4115
+ return false;
4116
+ }
4117
+ const elementSelectors = this.getElementSelectors(target);
4118
+ if (elementSelectors && elementSelectors.length > 0) {
4119
+ props['$element_selectors'] = elementSelectors;
4120
+ }
4121
+ if (eventName === COPY_AUTOCAPTURE_EVENT) {
4122
+ // you can't read the data from the clipboard event,
4123
+ // but you can guess that you can read it from the window's current selection
4124
+ const selectedContent = makeSafeText(win?.getSelection()?.toString());
4125
+ const clipType = e.type || 'clipboard';
4126
+ if (!selectedContent) {
4127
+ return false;
4128
+ }
4129
+ props['$selected_content'] = selectedContent;
4130
+ props['$copy_type'] = clipType;
4131
+ }
4132
+ this.instance.capture(eventName, props);
4133
+ return true;
4134
+ }
4135
+ }
4136
+ isBrowserSupported() {
4137
+ return isFunction(document?.querySelectorAll);
4138
+ }
4139
+ }
4140
+
4141
+ // This keeps track of the PageView state (such as the previous PageView's path, timestamp, id, and scroll properties).
4142
+ // We store the state in memory, which means that for non-SPA sites, the state will be lost on page reload. This means
4143
+ // that non-SPA sites should always send a $pageleave event on any navigation, before the page unloads. For SPA sites,
4144
+ // they only need to send a $pageleave event when the user navigates away from the site, as the information is not lost
4145
+ // on an internal navigation, and is included as the $prev_pageview_ properties in the next $pageview event.
4146
+ // Practically, this means that to find the scroll properties for a given pageview, you need to find the event where
4147
+ // event name is $pageview or $pageleave and where $prev_pageview_id matches the original pageview event's id.
4148
+ class PageViewManager {
4149
+ constructor(instance) {
4150
+ this._instance = instance;
4151
+ }
4152
+ doPageView(timestamp, pageViewId) {
4153
+ const response = this._previousPageViewProperties(timestamp, pageViewId);
4154
+ // On a pageview we reset the contexts
4155
+ this._currentPageview = {
4156
+ pathname: win?.location.pathname ?? '',
4157
+ pageViewId,
4158
+ timestamp
4159
+ };
4160
+ this._instance.scrollManager.resetContext();
4161
+ return response;
4162
+ }
4163
+ doPageLeave(timestamp) {
4164
+ return this._previousPageViewProperties(timestamp, this._currentPageview?.pageViewId);
4165
+ }
4166
+ doEvent() {
4167
+ return {
4168
+ $pageview_id: this._currentPageview?.pageViewId
4169
+ };
4170
+ }
4171
+ _previousPageViewProperties(timestamp, pageviewId) {
4172
+ const previousPageView = this._currentPageview;
4173
+ if (!previousPageView) {
4174
+ return {
4175
+ $pageview_id: pageviewId
4176
+ };
4177
+ }
4178
+ let properties = {
4179
+ $pageview_id: pageviewId,
4180
+ $prev_pageview_id: previousPageView.pageViewId
4181
+ };
4182
+ const scrollContext = this._instance.scrollManager.getContext();
4183
+ if (scrollContext && !this._instance.config.disable_scroll_properties) {
4184
+ let {
4185
+ maxScrollHeight,
4186
+ lastScrollY,
4187
+ maxScrollY,
4188
+ maxContentHeight,
4189
+ lastContentY,
4190
+ maxContentY
4191
+ } = scrollContext;
4192
+ if (!isUndefined(maxScrollHeight) && !isUndefined(lastScrollY) && !isUndefined(maxScrollY) && !isUndefined(maxContentHeight) && !isUndefined(lastContentY) && !isUndefined(maxContentY)) {
4193
+ // Use ceil, so that e.g. scrolling 999.5px of a 1000px page is considered 100% scrolled
4194
+ maxScrollHeight = Math.ceil(maxScrollHeight);
4195
+ lastScrollY = Math.ceil(lastScrollY);
4196
+ maxScrollY = Math.ceil(maxScrollY);
4197
+ maxContentHeight = Math.ceil(maxContentHeight);
4198
+ lastContentY = Math.ceil(lastContentY);
4199
+ maxContentY = Math.ceil(maxContentY);
4200
+ // if the maximum scroll height is near 0, then the percentage is 1
4201
+ const lastScrollPercentage = maxScrollHeight <= 1 ? 1 : clampToRange(lastScrollY / maxScrollHeight, 0, 1, logger);
4202
+ const maxScrollPercentage = maxScrollHeight <= 1 ? 1 : clampToRange(maxScrollY / maxScrollHeight, 0, 1, logger);
4203
+ const lastContentPercentage = maxContentHeight <= 1 ? 1 : clampToRange(lastContentY / maxContentHeight, 0, 1, logger);
4204
+ const maxContentPercentage = maxContentHeight <= 1 ? 1 : clampToRange(maxContentY / maxContentHeight, 0, 1, logger);
4205
+ properties = extend(properties, {
4206
+ $prev_pageview_last_scroll: lastScrollY,
4207
+ $prev_pageview_last_scroll_percentage: lastScrollPercentage,
4208
+ $prev_pageview_max_scroll: maxScrollY,
4209
+ $prev_pageview_max_scroll_percentage: maxScrollPercentage,
4210
+ $prev_pageview_last_content: lastContentY,
4211
+ $prev_pageview_last_content_percentage: lastContentPercentage,
4212
+ $prev_pageview_max_content: maxContentY,
4213
+ $prev_pageview_max_content_percentage: maxContentPercentage
4214
+ });
4215
+ }
4216
+ }
4217
+ if (previousPageView.pathname) {
4218
+ properties.$prev_pageview_pathname = previousPageView.pathname;
4219
+ }
4220
+ if (previousPageView.timestamp) {
4221
+ // Use seconds, for consistency with our other duration-related properties like $duration
4222
+ properties.$prev_pageview_duration = (timestamp.getTime() - previousPageView.timestamp.getTime()) / 1000;
4223
+ }
4224
+ return properties;
4225
+ }
4226
+ }
4227
+
4228
+ // This class is responsible for tracking scroll events and maintaining the scroll context
4229
+ class ScrollManager {
4230
+ constructor(_instance) {
4231
+ this._instance = _instance;
4232
+ this._updateScrollData = () => {
4233
+ if (!this._context) {
4234
+ this._context = {};
4235
+ }
4236
+ const el = this.scrollElement();
4237
+ const scrollY = this.scrollY();
4238
+ const scrollHeight = el ? Math.max(0, el.scrollHeight - el.clientHeight) : 0;
4239
+ const contentY = scrollY + (el?.clientHeight || 0);
4240
+ const contentHeight = el?.scrollHeight || 0;
4241
+ this._context.lastScrollY = Math.ceil(scrollY);
4242
+ this._context.maxScrollY = Math.max(scrollY, this._context.maxScrollY ?? 0);
4243
+ this._context.maxScrollHeight = Math.max(scrollHeight, this._context.maxScrollHeight ?? 0);
4244
+ this._context.lastContentY = contentY;
4245
+ this._context.maxContentY = Math.max(contentY, this._context.maxContentY ?? 0);
4246
+ this._context.maxContentHeight = Math.max(contentHeight, this._context.maxContentHeight ?? 0);
4247
+ };
4248
+ }
4249
+ getContext() {
4250
+ return this._context;
4251
+ }
4252
+ resetContext() {
4253
+ const ctx = this._context;
4254
+ // update the scroll properties for the new page, but wait until the next tick
4255
+ // of the event loop
4256
+ setTimeout(this._updateScrollData, 0);
4257
+ return ctx;
4258
+ }
4259
+ // `capture: true` is required to get scroll events for other scrollable elements
4260
+ // on the page, not just the window
4261
+ // see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#usecapture
4262
+ startMeasuringScrollPosition() {
4263
+ addEventListener(win, 'scroll', this._updateScrollData, {
4264
+ capture: true
4265
+ });
4266
+ addEventListener(win, 'scrollend', this._updateScrollData, {
4267
+ capture: true
4268
+ });
4269
+ addEventListener(win, 'resize', this._updateScrollData);
4270
+ }
4271
+ scrollElement() {
4272
+ if (this._instance.config.scroll_root_selector) {
4273
+ const selectors = isArray(this._instance.config.scroll_root_selector) ? this._instance.config.scroll_root_selector : [this._instance.config.scroll_root_selector];
4274
+ for (const selector of selectors) {
4275
+ const element = win?.document.querySelector(selector);
4276
+ if (element) {
4277
+ return element;
4278
+ }
4279
+ }
4280
+ return undefined;
4281
+ } else {
4282
+ return win?.document.documentElement;
4283
+ }
4284
+ }
4285
+ scrollY() {
4286
+ if (this._instance.config.scroll_root_selector) {
4287
+ const element = this.scrollElement();
4288
+ return element && element.scrollTop || 0;
4289
+ } else {
4290
+ return win ? win.scrollY || win.pageYOffset || win.document.documentElement.scrollTop || 0 : 0;
4291
+ }
4292
+ }
4293
+ scrollX() {
4294
+ if (this._instance.config.scroll_root_selector) {
4295
+ const element = this.scrollElement();
4296
+ return element && element.scrollLeft || 0;
4297
+ } else {
4298
+ return win ? win.scrollX || win.pageXOffset || win.document.documentElement.scrollLeft || 0 : 0;
4299
+ }
4300
+ }
4301
+ }
4302
+
4303
+ const DEFAULT_BLOCKED_UA_STRS = [
4304
+ // Random assortment of bots
4305
+ 'amazonbot', 'amazonproductbot', 'app.hypefactors.com',
4306
+ // Buck, but "buck" is too short to be safe to block (https://app.hypefactors.com/media-monitoring/about.htm)
4307
+ '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',
4308
+ // Bot-like words, maybe we should block `bot` entirely?
4309
+ 'bot.htm', 'bot.php', '(bot;', 'bot/', 'crawler',
4310
+ // Ahrefs: https://ahrefs.com/seo/glossary/ahrefsbot
4311
+ 'ahrefsbot', 'ahrefssiteaudit',
4312
+ // Semrush bots: https://www.semrush.com/bot/
4313
+ 'semrushbot', 'siteauditbot', 'splitsignalbot',
4314
+ // AI Crawlers
4315
+ 'gptbot', 'oai-searchbot', 'chatgpt-user', 'perplexitybot',
4316
+ // Uptime-like stuff
4317
+ 'better uptime bot', 'sentryuptimebot', 'uptimerobot',
4318
+ // headless browsers
4319
+ 'headlesschrome', 'cypress',
4320
+ // we don't block electron here, as many customers use posthog-js in electron apps
4321
+ // a whole bunch of goog-specific crawlers
4322
+ // https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers
4323
+ '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'];
4324
+ /**
4325
+ * Block various web spiders from executing our JS and sending false capturing data
4326
+ */
4327
+ const isBlockedUA = function (ua, customBlockedUserAgents) {
4328
+ if (!ua) {
4329
+ return false;
4330
+ }
4331
+ const uaLower = ua.toLowerCase();
4332
+ return DEFAULT_BLOCKED_UA_STRS.concat(customBlockedUserAgents || []).some(blockedUA => {
4333
+ const blockedUaLower = blockedUA.toLowerCase();
4334
+ // can't use includes because IE 11 :/
4335
+ return uaLower.indexOf(blockedUaLower) !== -1;
4336
+ });
4337
+ };
4338
+ const isLikelyBot = function (navigator, customBlockedUserAgents) {
4339
+ if (!navigator) {
4340
+ return false;
4341
+ }
4342
+ const ua = navigator.userAgent;
4343
+ if (ua) {
4344
+ if (isBlockedUA(ua, customBlockedUserAgents)) {
4345
+ return true;
4346
+ }
4347
+ }
4348
+ try {
4349
+ // eslint-disable-next-line compat/compat
4350
+ const uaData = navigator?.userAgentData;
4351
+ if (uaData?.brands && uaData.brands.some(brandObj => isBlockedUA(brandObj?.brand, customBlockedUserAgents))) {
4352
+ return true;
4353
+ }
4354
+ } catch {
4355
+ // ignore the error, we were using experimental browser features
4356
+ }
4357
+ return !!navigator.webdriver;
4358
+ // There's some more enhancements we could make in this area, e.g. it's possible to check if Chrome dev tools are
4359
+ // open, which will detect some bots that are trying to mask themselves and might get past the checks above.
4360
+ // However, this would give false positives for actual humans who have dev tools open.
4361
+ // We could also use the data in navigator.userAgentData.getHighEntropyValues() to detect bots, but we should wait
4362
+ // until this stops being experimental. The MDN docs imply that this might eventually require user permission.
4363
+ // See https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/getHighEntropyValues
4364
+ // It would be very bad if posthog-js caused a permission prompt to appear on every page load.
4365
+ };
4366
+
4367
+ const defaultConfig = () => ({
4368
+ host: 'https://i.leanbase.co',
4369
+ token: '',
4370
+ autocapture: true,
4371
+ rageclick: true,
4372
+ persistence: 'localStorage+cookie',
4373
+ capture_pageview: 'history_change',
4374
+ capture_pageleave: 'if_capture_pageview',
4375
+ persistence_name: '',
4376
+ mask_all_element_attributes: false,
4377
+ cookie_expiration: 365,
4378
+ cross_subdomain_cookie: isCrossDomainCookie(document?.location),
4379
+ custom_campaign_params: [],
4380
+ custom_personal_data_properties: [],
4381
+ disable_persistence: false,
4382
+ mask_personal_data_properties: false,
4383
+ secure_cookie: window?.location?.protocol === 'https:',
4384
+ mask_all_text: false,
4385
+ bootstrap: {},
4386
+ session_idle_timeout_seconds: 30 * 60,
4387
+ save_campaign_params: true,
4388
+ save_referrer: true,
4389
+ opt_out_useragent_filter: false,
4390
+ properties_string_max_length: 65535,
4391
+ loaded: () => {}
4392
+ });
4393
+ class Leanbase extends PostHogCore {
4394
+ constructor(token, config) {
4395
+ const mergedConfig = extend(defaultConfig(), config || {}, {
4396
+ token
4397
+ });
4398
+ super(token, mergedConfig);
4399
+ this.personProcessingSetOncePropertiesSent = false;
4400
+ this.isLoaded = false;
4401
+ this.config = mergedConfig;
4402
+ this.visibilityStateListener = null;
4403
+ this.initialPageviewCaptured = false;
4404
+ this.scrollManager = new ScrollManager(this);
4405
+ this.pageViewManager = new PageViewManager(this);
4406
+ this.init(token, mergedConfig);
4407
+ }
4408
+ init(token, config) {
4409
+ this.setConfig(extend(defaultConfig(), config, {
4410
+ token
4411
+ }));
4412
+ this.isLoaded = true;
4413
+ this.persistence = new LeanbasePersistence(this.config);
4414
+ this.replayAutocapture = new Autocapture(this);
4415
+ this.replayAutocapture.startIfEnabled();
4416
+ if (this.config.preloadFeatureFlags !== false) {
4417
+ this.reloadFeatureFlags();
4418
+ }
4419
+ this.config.loaded?.(this);
4420
+ if (this.config.capture_pageview) {
4421
+ setTimeout(() => {
4422
+ if (this.config.cookieless_mode === 'always') {
4423
+ this.captureInitialPageview();
4424
+ }
4425
+ }, 1);
4426
+ }
4427
+ addEventListener(document, 'DOMContentLoaded', () => {
4428
+ this.loadRemoteConfig();
4429
+ });
4430
+ addEventListener(window, 'onpagehide' in self ? 'pagehide' : 'unload', this.capturePageLeave.bind(this), {
4431
+ passive: false
4432
+ });
4433
+ }
4434
+ captureInitialPageview() {
4435
+ if (!document) {
4436
+ return;
4437
+ }
4438
+ if (document.visibilityState !== 'visible') {
4439
+ if (!this.visibilityStateListener) {
4440
+ this.visibilityStateListener = this.captureInitialPageview.bind(this);
4441
+ addEventListener(document, 'visibilitychange', this.visibilityStateListener);
4442
+ }
4443
+ return;
4444
+ }
4445
+ if (!this.initialPageviewCaptured) {
4446
+ this.initialPageviewCaptured = true;
4447
+ this.capture('$pageview', {
4448
+ title: document.title
4449
+ });
4450
+ if (this.visibilityStateListener) {
4451
+ document.removeEventListener('visibilitychange', this.visibilityStateListener);
4452
+ this.visibilityStateListener = null;
4453
+ }
4454
+ }
4455
+ }
4456
+ capturePageLeave() {
4457
+ const {
4458
+ capture_pageleave,
4459
+ capture_pageview
4460
+ } = this.config;
4461
+ if (capture_pageleave === true || capture_pageleave === 'if_capture_pageview' && (capture_pageview === true || capture_pageview === 'history_change')) {
4462
+ this.capture('$pageleave');
4463
+ }
4464
+ }
4465
+ async loadRemoteConfig() {
4466
+ if (!this.isRemoteConfigLoaded) {
4467
+ const remoteConfig = await this.reloadRemoteConfigAsync();
4468
+ if (remoteConfig) {
4469
+ this.onRemoteConfig(remoteConfig);
4470
+ }
4471
+ }
4472
+ }
4473
+ onRemoteConfig(config) {
4474
+ if (!(document && document.body)) {
4475
+ setTimeout(() => {
4476
+ this.onRemoteConfig(config);
4477
+ }, 500);
4478
+ return;
4479
+ }
4480
+ this.isRemoteConfigLoaded = true;
4481
+ this.replayAutocapture?.onRemoteConfig(config);
4482
+ }
4483
+ fetch(url, options) {
4484
+ const fetchFn = getFetch();
4485
+ if (!fetchFn) {
4486
+ return Promise.reject(new Error('Fetch API is not available in this environment.'));
4487
+ }
4488
+ return fetchFn(url, options);
4489
+ }
4490
+ setConfig(config) {
4491
+ const oldConfig = {
4492
+ ...this.config
4493
+ };
4494
+ if (isObject(config)) {
4495
+ extend(this.config, config);
4496
+ this.persistence?.update_config(this.config, oldConfig);
4497
+ this.replayAutocapture?.startIfEnabled();
4498
+ }
4499
+ const isTempStorage = this.config.persistence === 'sessionStorage' || this.config.persistence === 'memory';
4500
+ this.sessionPersistence = isTempStorage ? this.persistence : new LeanbasePersistence({
4501
+ ...this.config,
4502
+ persistence: 'sessionStorage'
4503
+ });
4504
+ }
4505
+ getLibraryId() {
4506
+ return 'leanbase';
4507
+ }
4508
+ getLibraryVersion() {
4509
+ return Config.LIB_VERSION;
4510
+ }
4511
+ getCustomUserAgent() {
4512
+ return;
4513
+ }
4514
+ getPersistedProperty(key) {
4515
+ return this.persistence?.get_property(key);
4516
+ }
4517
+ setPersistedProperty(key, value) {
4518
+ this.persistence?.set_property(key, value);
4519
+ }
4520
+ calculateEventProperties(eventName, eventProperties, timestamp, uuid, readOnly) {
4521
+ if (!this.persistence || !this.sessionPersistence) {
4522
+ return eventProperties;
4523
+ }
4524
+ timestamp = timestamp || new Date();
4525
+ const startTimestamp = readOnly ? undefined : this.persistence?.remove_event_timer(eventName);
4526
+ let properties = {
4527
+ ...eventProperties
4528
+ };
4529
+ properties['token'] = this.config.token;
4530
+ if (this.config.cookieless_mode == 'always' || this.config.cookieless_mode == 'on_reject') {
4531
+ properties[COOKIELESS_MODE_FLAG_PROPERTY] = true;
4532
+ }
4533
+ if (eventName === '$snapshot') {
4534
+ const persistenceProps = {
4535
+ ...this.persistence.properties()
4536
+ };
4537
+ properties['distinct_id'] = persistenceProps.distinct_id;
4538
+ if (!(isString(properties['distinct_id']) || isNumber(properties['distinct_id'])) || isEmptyString(properties['distinct_id'])) {
4539
+ logger.error('Invalid distinct_id for replay event. This indicates a bug in your implementation');
4540
+ }
4541
+ return properties;
4542
+ }
4543
+ const infoProperties = getEventProperties(this.config.mask_personal_data_properties, this.config.custom_personal_data_properties);
4544
+ if (this.sessionManager) {
4545
+ const {
4546
+ sessionId,
4547
+ windowId
4548
+ } = this.sessionManager.checkAndGetSessionAndWindowId(readOnly, timestamp.getTime());
4549
+ properties['$session_id'] = sessionId;
4550
+ properties['$window_id'] = windowId;
4551
+ }
4552
+ if (this.sessionPropsManager) {
4553
+ extend(properties, this.sessionPropsManager.getSessionProps());
4554
+ }
4555
+ let pageviewProperties = this.pageViewManager.doEvent();
4556
+ if (eventName === '$pageview' && !readOnly) {
4557
+ pageviewProperties = this.pageViewManager.doPageView(timestamp, uuid);
4558
+ }
4559
+ if (eventName === '$pageleave' && !readOnly) {
4560
+ pageviewProperties = this.pageViewManager.doPageLeave(timestamp);
4561
+ }
4562
+ properties = extend(properties, pageviewProperties);
4563
+ if (eventName === '$pageview' && document) {
4564
+ properties['title'] = document.title;
4565
+ }
4566
+ if (!isUndefined(startTimestamp)) {
4567
+ const duration_in_ms = timestamp.getTime() - startTimestamp;
4568
+ properties['$duration'] = parseFloat((duration_in_ms / 1000).toFixed(3));
4569
+ }
4570
+ if (userAgent && this.config.opt_out_useragent_filter) {
4571
+ properties['$browser_type'] = isLikelyBot(navigator$1, []) ? 'bot' : 'browser';
4572
+ }
4573
+ properties = extend({}, infoProperties, this.persistence.properties(), this.sessionPersistence.properties(), properties);
4574
+ properties['$is_identified'] = this.isIdentified();
4575
+ return properties;
4576
+ }
4577
+ isIdentified() {
4578
+ return this.persistence?.get_property(USER_STATE) === 'identified' || this.sessionPersistence?.get_property(USER_STATE) === 'identified';
4579
+ }
4580
+ /**
4581
+ * Add additional set_once properties to the event when creating a person profile. This allows us to create the
4582
+ * profile with mostly-accurate properties, despite earlier events not setting them. We do this by storing them in
4583
+ * persistence.
4584
+ * @param dataSetOnce
4585
+ */
4586
+ calculateSetOnceProperties(dataSetOnce) {
4587
+ if (!this.persistence) {
4588
+ return dataSetOnce;
4589
+ }
4590
+ if (this.personProcessingSetOncePropertiesSent) {
4591
+ return dataSetOnce;
4592
+ }
4593
+ const initialProps = this.persistence.get_initial_props();
4594
+ const sessionProps = this.sessionPropsManager?.getSetOnceProps();
4595
+ const setOnceProperties = extend({}, initialProps, sessionProps || {}, dataSetOnce || {});
4596
+ this.personProcessingSetOncePropertiesSent = true;
4597
+ if (isEmptyObject(setOnceProperties)) {
4598
+ return undefined;
4599
+ }
4600
+ return setOnceProperties;
4601
+ }
4602
+ capture(event, properties, options) {
4603
+ if (!this.isLoaded || !this.sessionPersistence || !this.persistence) {
4604
+ return;
4605
+ }
4606
+ if (isUndefined(event) || !isString(event)) {
4607
+ logger.error('No event name provided to posthog.capture');
4608
+ return;
4609
+ }
4610
+ if (properties?.$current_url && !isString(properties?.$current_url)) {
4611
+ logger.error('Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value.');
4612
+ delete properties?.$current_url;
4613
+ }
4614
+ this.sessionPersistence.update_search_keyword();
4615
+ if (this.config.save_campaign_params) {
4616
+ this.sessionPersistence.update_campaign_params();
4617
+ }
4618
+ if (this.config.save_referrer) {
4619
+ this.sessionPersistence.update_referrer_info();
4620
+ }
4621
+ if (this.config.save_campaign_params || this.config.save_referrer) {
4622
+ this.persistence.set_initial_person_info();
4623
+ }
4624
+ const systemTime = new Date();
4625
+ const timestamp = options?.timestamp || systemTime;
4626
+ const uuid = uuidv7();
4627
+ let data = {
4628
+ uuid,
4629
+ event,
4630
+ properties: this.calculateEventProperties(event, properties || {}, timestamp, uuid)
4631
+ };
4632
+ const setProperties = options?.$set;
4633
+ if (setProperties) {
4634
+ data.$set = options?.$set;
4635
+ }
4636
+ const setOnceProperties = this.calculateSetOnceProperties(options?.$set_once);
4637
+ if (setOnceProperties) {
4638
+ data.$set_once = setOnceProperties;
4639
+ }
4640
+ data = copyAndTruncateStrings(data, options?._noTruncate ? null : this.config.properties_string_max_length);
4641
+ data.timestamp = timestamp;
4642
+ if (!isUndefined(options?.timestamp)) {
4643
+ data.properties['$event_time_override_provided'] = true;
4644
+ data.properties['$event_time_override_system_time'] = systemTime;
4645
+ }
4646
+ const finalSet = {
4647
+ ...data.properties['$set'],
4648
+ ...data['$set']
4649
+ };
4650
+ if (!isEmptyObject(finalSet)) {
4651
+ this.setPersonPropertiesForFlags(finalSet);
4652
+ }
4653
+ super.capture(data.event, data.properties, options);
4654
+ }
4655
+ identify(distinctId, properties, options) {
4656
+ super.identify(distinctId, properties, options);
4657
+ }
4658
+ destroy() {
4659
+ this.persistence?.clear();
4660
+ }
4661
+ }
4662
+
4663
+ const api = {
4664
+ _instance: null,
4665
+ _queue: [],
4666
+ init(apiKey, options) {
4667
+ this._instance = new Leanbase(apiKey, options);
4668
+ const q = this._queue;
4669
+ this._queue = [];
4670
+ for (const {
4671
+ fn,
4672
+ args
4673
+ } of q) {
4674
+ // @ts-expect-error dynamic dispatch to API methods
4675
+ this[fn](...args);
4676
+ }
4677
+ },
4678
+ capture(...args) {
4679
+ if (this._instance) {
4680
+ return this._instance.capture(...args);
4681
+ }
4682
+ this._queue.push({
4683
+ fn: 'capture',
4684
+ args
4685
+ });
4686
+ },
4687
+ captureException(...args) {
4688
+ if (this._instance) {
4689
+ return this._instance.captureException(...args);
4690
+ }
4691
+ this._queue.push({
4692
+ fn: 'captureException',
4693
+ args
4694
+ });
4695
+ },
4696
+ identify(...args) {
4697
+ if (this._instance) {
4698
+ return this._instance.identify(...args);
4699
+ }
4700
+ this._queue.push({
4701
+ fn: 'identify',
4702
+ args
4703
+ });
4704
+ },
4705
+ group(...args) {
4706
+ if (this._instance) {
4707
+ return this._instance.group(...args);
4708
+ }
4709
+ this._queue.push({
4710
+ fn: 'group',
4711
+ args
4712
+ });
4713
+ },
4714
+ alias(...args) {
4715
+ if (this._instance) {
4716
+ return this._instance.alias(...args);
4717
+ }
4718
+ this._queue.push({
4719
+ fn: 'alias',
4720
+ args
4721
+ });
1763
4722
  },
1764
4723
  reset() {
1765
4724
  this._instance?.reset();