posthog-js-lite 3.0.1 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs.js CHANGED
@@ -18,6 +18,7 @@ var PostHogPersistedProperty;
18
18
  PostHogPersistedProperty["GroupProperties"] = "group_properties";
19
19
  PostHogPersistedProperty["InstalledAppBuild"] = "installed_app_build";
20
20
  PostHogPersistedProperty["InstalledAppVersion"] = "installed_app_version";
21
+ PostHogPersistedProperty["SessionReplay"] = "session_replay";
21
22
  })(PostHogPersistedProperty || (PostHogPersistedProperty = {}));
22
23
 
23
24
  function assert(truthyValue, message) {
@@ -948,6 +949,7 @@ class PostHogCoreStateless {
948
949
  constructor(apiKey, options) {
949
950
  this.flushPromise = null;
950
951
  this.disableGeoip = true;
952
+ this.historicalMigration = false;
951
953
  this.disabled = false;
952
954
  this.defaultOptIn = true;
953
955
  this.pendingPromises = {};
@@ -956,12 +958,12 @@ class PostHogCoreStateless {
956
958
  this._isInitialized = false;
957
959
  assert(apiKey, "You must pass your PostHog project's api key.");
958
960
  this.apiKey = apiKey;
959
- this.host = removeTrailingSlash(options?.host || 'https://app.posthog.com');
961
+ this.host = removeTrailingSlash(options?.host || 'https://us.i.posthog.com');
960
962
  this.flushAt = options?.flushAt ? Math.max(options?.flushAt, 1) : 20;
961
963
  this.maxBatchSize = Math.max(this.flushAt, options?.maxBatchSize ?? 100);
962
964
  this.maxQueueSize = Math.max(this.flushAt, options?.maxQueueSize ?? 1000);
963
965
  this.flushInterval = options?.flushInterval ?? 10000;
964
- this.captureMode = options?.captureMode || 'form';
966
+ this.captureMode = options?.captureMode || 'json';
965
967
  // If enable is explicitly set to false we override the optout
966
968
  this.defaultOptIn = options?.defaultOptIn ?? true;
967
969
  this._retryOptions = {
@@ -973,15 +975,19 @@ class PostHogCoreStateless {
973
975
  this.featureFlagsRequestTimeoutMs = options?.featureFlagsRequestTimeoutMs ?? 3000; // 3 seconds
974
976
  this.disableGeoip = options?.disableGeoip ?? true;
975
977
  this.disabled = options?.disabled ?? false;
978
+ this.historicalMigration = options?.historicalMigration ?? false;
976
979
  // Init promise allows the derived class to block calls until it is ready
977
980
  this._initPromise = Promise.resolve();
978
981
  this._isInitialized = true;
979
982
  }
983
+ logMsgIfDebug(fn) {
984
+ if (this.isDebug) {
985
+ fn();
986
+ }
987
+ }
980
988
  wrap(fn) {
981
989
  if (this.disabled) {
982
- if (this.isDebug) {
983
- console.warn('[PostHog] The client is disabled');
984
- }
990
+ this.logMsgIfDebug(() => console.warn('[PostHog] The client is disabled'));
985
991
  return;
986
992
  }
987
993
  if (this._isInitialized) {
@@ -1025,6 +1031,9 @@ class PostHogCoreStateless {
1025
1031
  get isDebug() {
1026
1032
  return !!this.removeDebugCallback;
1027
1033
  }
1034
+ get isDisabled() {
1035
+ return this.disabled;
1036
+ }
1028
1037
  buildPayload(payload) {
1029
1038
  return {
1030
1039
  distinct_id: payload.distinct_id,
@@ -1051,7 +1060,7 @@ class PostHogCoreStateless {
1051
1060
  identifyStateless(distinctId, properties, options) {
1052
1061
  this.wrap(() => {
1053
1062
  // The properties passed to identifyStateless are event properties.
1054
- // To add person properties, pass in all person properties to the `$set` key.
1063
+ // To add person properties, pass in all person properties to the `$set` and `$set_once` keys.
1055
1064
  const payload = {
1056
1065
  ...this.buildPayload({
1057
1066
  distinct_id: distinctId,
@@ -1221,7 +1230,7 @@ class PostHogCoreStateless {
1221
1230
  const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1222
1231
  if (queue.length >= this.maxQueueSize) {
1223
1232
  queue.shift();
1224
- console.info('Queue is full, the oldest event is dropped.');
1233
+ this.logMsgIfDebug(() => console.info('Queue is full, the oldest event is dropped.'));
1225
1234
  }
1226
1235
  queue.push({ message });
1227
1236
  this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
@@ -1287,6 +1296,9 @@ class PostHogCoreStateless {
1287
1296
  batch: messages,
1288
1297
  sent_at: currentISOTime(),
1289
1298
  };
1299
+ if (this.historicalMigration) {
1300
+ data.historical_migration = true;
1301
+ }
1290
1302
  const payload = JSON.stringify(data);
1291
1303
  const url = this.captureMode === 'form'
1292
1304
  ? `${this.host}/e/?ip=1&_=${currentTimestamp()}&v=${this.getLibraryVersion()}`
@@ -1350,33 +1362,45 @@ class PostHogCoreStateless {
1350
1362
  }, { ...this._retryOptions, ...retryOptions });
1351
1363
  }
1352
1364
  async shutdown(shutdownTimeoutMs = 30000) {
1365
+ // A little tricky - we want to have a max shutdown time and enforce it, even if that means we have some
1366
+ // dangling promises. We'll keep track of the timeout and resolve/reject based on that.
1353
1367
  await this._initPromise;
1368
+ let hasTimedOut = false;
1354
1369
  this.clearFlushTimer();
1355
- try {
1356
- await Promise.all(Object.values(this.pendingPromises));
1357
- const startTimeWithDelay = Date.now() + shutdownTimeoutMs;
1358
- while (true) {
1359
- const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1360
- if (queue.length === 0) {
1361
- break;
1362
- }
1363
- // flush again to make sure we send all events, some of which might've been added
1364
- // while we were waiting for the pending promises to resolve
1365
- // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
1366
- await this.flush();
1367
- // If we've been waiting for more than the shutdownTimeoutMs, stop it
1368
- const now = Date.now();
1369
- if (startTimeWithDelay < now) {
1370
- break;
1370
+ const doShutdown = async () => {
1371
+ try {
1372
+ await Promise.all(Object.values(this.pendingPromises));
1373
+ while (true) {
1374
+ const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1375
+ if (queue.length === 0) {
1376
+ break;
1377
+ }
1378
+ // flush again to make sure we send all events, some of which might've been added
1379
+ // while we were waiting for the pending promises to resolve
1380
+ // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
1381
+ await this.flush();
1382
+ if (hasTimedOut) {
1383
+ break;
1384
+ }
1371
1385
  }
1372
1386
  }
1373
- }
1374
- catch (e) {
1375
- if (!isPostHogFetchError(e)) {
1376
- throw e;
1387
+ catch (e) {
1388
+ if (!isPostHogFetchError(e)) {
1389
+ throw e;
1390
+ }
1391
+ this.logMsgIfDebug(() => console.error('Error while shutting down PostHog', e));
1377
1392
  }
1378
- console.error('Error while shutting down PostHog', e);
1379
- }
1393
+ };
1394
+ return Promise.race([
1395
+ new Promise((_, reject) => {
1396
+ safeSetTimeout(() => {
1397
+ this.logMsgIfDebug(() => console.error('Timed out while shutting down PostHog'));
1398
+ hasTimedOut = true;
1399
+ reject('Timeout while shutting down PostHog. Some events may not have been sent.');
1400
+ }, shutdownTimeoutMs);
1401
+ }),
1402
+ doShutdown(),
1403
+ ]);
1380
1404
  }
1381
1405
  }
1382
1406
  class PostHogCore extends PostHogCoreStateless {
@@ -1392,20 +1416,42 @@ class PostHogCore extends PostHogCoreStateless {
1392
1416
  this._sessionExpirationTimeSeconds = options?.sessionExpirationTimeSeconds ?? 1800; // 30 minutes
1393
1417
  }
1394
1418
  setupBootstrap(options) {
1395
- if (options?.bootstrap?.distinctId) {
1396
- if (options?.bootstrap?.isIdentifiedId) {
1397
- this.setPersistedProperty(PostHogPersistedProperty.DistinctId, options.bootstrap.distinctId);
1419
+ const bootstrap = options?.bootstrap;
1420
+ if (!bootstrap) {
1421
+ return;
1422
+ }
1423
+ // bootstrap options are only set if no persisted values are found
1424
+ // this is to prevent overwriting existing values
1425
+ if (bootstrap.distinctId) {
1426
+ if (bootstrap.isIdentifiedId) {
1427
+ const distinctId = this.getPersistedProperty(PostHogPersistedProperty.DistinctId);
1428
+ if (!distinctId) {
1429
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, bootstrap.distinctId);
1430
+ }
1398
1431
  }
1399
1432
  else {
1400
- this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, options.bootstrap.distinctId);
1433
+ const anonymousId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
1434
+ if (!anonymousId) {
1435
+ this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, bootstrap.distinctId);
1436
+ }
1401
1437
  }
1402
1438
  }
1403
- if (options?.bootstrap?.featureFlags) {
1404
- const activeFlags = Object.keys(options.bootstrap?.featureFlags || {})
1405
- .filter((flag) => !!options.bootstrap?.featureFlags?.[flag])
1406
- .reduce((res, key) => ((res[key] = options.bootstrap?.featureFlags?.[key] || false), res), {});
1407
- this.setKnownFeatureFlags(activeFlags);
1408
- options?.bootstrap.featureFlagPayloads && this.setKnownFeatureFlagPayloads(options?.bootstrap.featureFlagPayloads);
1439
+ const bootstrapfeatureFlags = bootstrap.featureFlags;
1440
+ if (bootstrapfeatureFlags && Object.keys(bootstrapfeatureFlags).length) {
1441
+ const bootstrapFlags = Object.keys(bootstrapfeatureFlags)
1442
+ .filter((flag) => !!bootstrapfeatureFlags[flag])
1443
+ .reduce((res, key) => ((res[key] = bootstrapfeatureFlags[key] || false), res), {});
1444
+ if (Object.keys(bootstrapFlags).length) {
1445
+ const currentFlags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags) || {};
1446
+ const newFeatureFlags = { ...bootstrapFlags, ...currentFlags };
1447
+ this.setKnownFeatureFlags(newFeatureFlags);
1448
+ }
1449
+ const bootstrapFlagPayloads = bootstrap.featureFlagPayloads;
1450
+ if (bootstrapFlagPayloads && Object.keys(bootstrapFlagPayloads).length) {
1451
+ const currentFlagPayloads = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads) || {};
1452
+ const newFeatureFlagPayloads = { ...bootstrapFlagPayloads, ...currentFlagPayloads };
1453
+ this.setKnownFeatureFlagPayloads(newFeatureFlagPayloads);
1454
+ }
1409
1455
  }
1410
1456
  }
1411
1457
  // NOTE: Props are lazy loaded from localstorage hence the complex getter setter logic
@@ -1421,6 +1467,7 @@ class PostHogCore extends PostHogCoreStateless {
1421
1467
  clearProps() {
1422
1468
  this.props = undefined;
1423
1469
  this.sessionProps = {};
1470
+ this.flagCallReported = {};
1424
1471
  }
1425
1472
  on(event, cb) {
1426
1473
  return this._events.on(event, cb);
@@ -1479,6 +1526,7 @@ class PostHogCore extends PostHogCoreStateless {
1479
1526
  resetSessionId() {
1480
1527
  this.wrap(() => {
1481
1528
  this.setPersistedProperty(PostHogPersistedProperty.SessionId, null);
1529
+ this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, null);
1482
1530
  });
1483
1531
  }
1484
1532
  /**
@@ -1538,10 +1586,15 @@ class PostHogCore extends PostHogCoreStateless {
1538
1586
  if (properties?.$groups) {
1539
1587
  this.groups(properties.$groups);
1540
1588
  }
1589
+ // promote $set and $set_once to top level
1590
+ const userPropsOnce = properties?.$set_once;
1591
+ delete properties?.$set_once;
1592
+ // if no $set is provided we assume all properties are $set
1593
+ const userProps = properties?.$set || properties;
1541
1594
  const allProperties = this.enrichProperties({
1542
- ...properties,
1543
1595
  $anon_distinct_id: this.getAnonymousId(),
1544
- $set: properties,
1596
+ $set: userProps,
1597
+ $set_once: userPropsOnce,
1545
1598
  });
1546
1599
  if (distinctId !== previousDistinctId) {
1547
1600
  // We keep the AnonymousId to be used by decide calls and identify to link the previousId
@@ -1695,6 +1748,10 @@ class PostHogCore extends PostHogCoreStateless {
1695
1748
  };
1696
1749
  return super.getDecide(distinctId, groups, personProperties, groupProperties, extraProperties).then((res) => {
1697
1750
  if (res?.featureFlags) {
1751
+ // clear flag call reported if we have new flags since they might have changed
1752
+ if (this.sendFeatureFlagEvent) {
1753
+ this.flagCallReported = {};
1754
+ }
1698
1755
  let newFeatureFlags = res.featureFlags;
1699
1756
  let newFeatureFlagPayloads = res.featureFlagPayloads;
1700
1757
  if (res.errorsWhileComputingFlags) {
@@ -1706,6 +1763,15 @@ class PostHogCore extends PostHogCoreStateless {
1706
1763
  }
1707
1764
  this.setKnownFeatureFlags(newFeatureFlags);
1708
1765
  this.setKnownFeatureFlagPayloads(Object.fromEntries(Object.entries(newFeatureFlagPayloads || {}).map(([k, v]) => [k, this._parsePayload(v)])));
1766
+ const sessionReplay = res?.sessionRecording;
1767
+ if (sessionReplay) {
1768
+ this.setPersistedProperty(PostHogPersistedProperty.SessionReplay, sessionReplay);
1769
+ this.logMsgIfDebug(() => console.log('PostHog Debug', 'Session replay config: ', JSON.stringify(sessionReplay)));
1770
+ }
1771
+ else {
1772
+ this.logMsgIfDebug(() => console.info('PostHog Debug', 'Session replay config disabled.'));
1773
+ this.setPersistedProperty(PostHogPersistedProperty.SessionReplay, null);
1774
+ }
1709
1775
  }
1710
1776
  return res;
1711
1777
  });
@@ -1807,7 +1873,7 @@ class PostHogCore extends PostHogCoreStateless {
1807
1873
  .catch((e) => {
1808
1874
  cb?.(e, undefined);
1809
1875
  if (!cb) {
1810
- console.log('[PostHog] Error reloading feature flags', e);
1876
+ this.logMsgIfDebug(() => console.log('[PostHog] Error reloading feature flags', e));
1811
1877
  }
1812
1878
  });
1813
1879
  }
@@ -1840,14 +1906,14 @@ class PostHogCore extends PostHogCoreStateless {
1840
1906
  }
1841
1907
  }
1842
1908
 
1843
- var version = "3.0.1";
1909
+ var version = "3.1.0";
1844
1910
 
1845
1911
  function getContext(window) {
1846
1912
  let context = {};
1847
-
1848
1913
  if (window.navigator) {
1849
1914
  const userAgent = window.navigator.userAgent;
1850
- context = { ...context,
1915
+ context = {
1916
+ ...context,
1851
1917
  $os: os(window),
1852
1918
  $browser: browser(userAgent, window.navigator.vendor, !!window.opera),
1853
1919
  $referrer: window.document.referrer,
@@ -1862,29 +1928,24 @@ function getContext(window) {
1862
1928
  $screen_dpr: window.devicePixelRatio
1863
1929
  };
1864
1930
  }
1865
-
1866
- context = { ...context,
1931
+ context = {
1932
+ ...context,
1867
1933
  $lib: 'js',
1868
1934
  $lib_version: version,
1869
1935
  $insert_id: Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10),
1870
1936
  $time: currentTimestamp() / 1000 // epoch time in seconds
1871
-
1872
1937
  };
1873
1938
  return context; // TODO: strip empty props?
1874
1939
  }
1875
-
1876
1940
  function includes(haystack, needle) {
1877
1941
  return haystack.indexOf(needle) >= 0;
1878
1942
  }
1879
-
1880
1943
  function browser(userAgent, vendor, opera) {
1881
1944
  vendor = vendor || ''; // vendor is undefined for at least IE9
1882
-
1883
1945
  if (opera || includes(userAgent, ' OPR/')) {
1884
1946
  if (includes(userAgent, 'Mini')) {
1885
1947
  return 'Opera Mini';
1886
1948
  }
1887
-
1888
1949
  return 'Opera';
1889
1950
  } else if (/(BlackBerry|PlayBook|BB10)/i.test(userAgent)) {
1890
1951
  return 'BlackBerry';
@@ -1909,7 +1970,6 @@ function browser(userAgent, vendor, opera) {
1909
1970
  if (includes(userAgent, 'Mobile')) {
1910
1971
  return 'Mobile Safari';
1911
1972
  }
1912
-
1913
1973
  return 'Safari';
1914
1974
  } else if (includes(userAgent, 'Android')) {
1915
1975
  return 'Android Mobile';
@@ -1925,7 +1985,6 @@ function browser(userAgent, vendor, opera) {
1925
1985
  return '';
1926
1986
  }
1927
1987
  }
1928
-
1929
1988
  function browserVersion(userAgent, vendor, opera) {
1930
1989
  const regexList = {
1931
1990
  'Internet Explorer Mobile': /rv:(\d+(\.\d+)?)/,
@@ -1947,28 +2006,21 @@ function browserVersion(userAgent, vendor, opera) {
1947
2006
  };
1948
2007
  const browserString = browser(userAgent, vendor, opera);
1949
2008
  const regex = regexList[browserString] || undefined;
1950
-
1951
2009
  if (regex === undefined) {
1952
2010
  return null;
1953
2011
  }
1954
-
1955
2012
  const matches = userAgent.match(regex);
1956
-
1957
2013
  if (!matches) {
1958
2014
  return null;
1959
2015
  }
1960
-
1961
2016
  return parseFloat(matches[matches.length - 2]);
1962
2017
  }
1963
-
1964
2018
  function os(window) {
1965
2019
  const a = window.navigator.userAgent;
1966
-
1967
2020
  if (/Windows/i.test(a)) {
1968
2021
  if (/Phone/.test(a) || /WPDesktop/.test(a)) {
1969
2022
  return 'Windows Phone';
1970
2023
  }
1971
-
1972
2024
  return 'Windows';
1973
2025
  } else if (/(iPhone|iPad|iPod)/.test(a)) {
1974
2026
  return 'iOS';
@@ -1986,7 +2038,6 @@ function os(window) {
1986
2038
  return '';
1987
2039
  }
1988
2040
  }
1989
-
1990
2041
  function device(userAgent) {
1991
2042
  if (/Windows Phone/i.test(userAgent) || /WPDesktop/.test(userAgent)) {
1992
2043
  return 'Windows Phone';
@@ -2004,14 +2055,11 @@ function device(userAgent) {
2004
2055
  return '';
2005
2056
  }
2006
2057
  }
2007
-
2008
2058
  function referringDomain(referrer) {
2009
2059
  const split = referrer.split('/');
2010
-
2011
2060
  if (split.length >= 3) {
2012
2061
  return split[2];
2013
2062
  }
2014
-
2015
2063
  return '';
2016
2064
  }
2017
2065
 
@@ -2021,35 +2069,29 @@ const cookieStore = {
2021
2069
  try {
2022
2070
  const nameEQ = key + '=';
2023
2071
  const ca = document.cookie.split(';');
2024
-
2025
2072
  for (let i = 0; i < ca.length; i++) {
2026
2073
  let c = ca[i];
2027
-
2028
2074
  while (c.charAt(0) == ' ') {
2029
2075
  c = c.substring(1, c.length);
2030
2076
  }
2031
-
2032
2077
  if (c.indexOf(nameEQ) === 0) {
2033
2078
  return decodeURIComponent(c.substring(nameEQ.length, c.length));
2034
2079
  }
2035
2080
  }
2036
2081
  } catch (err) {}
2037
-
2038
2082
  return null;
2039
2083
  },
2040
-
2041
2084
  setItem(key, value) {
2042
2085
  try {
2043
2086
  const cdomain = '',
2044
- expires = '',
2045
- secure = '';
2087
+ expires = '',
2088
+ secure = '';
2046
2089
  const new_cookie_val = key + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
2047
2090
  document.cookie = new_cookie_val;
2048
2091
  } catch (err) {
2049
2092
  return;
2050
2093
  }
2051
2094
  },
2052
-
2053
2095
  removeItem(name) {
2054
2096
  try {
2055
2097
  cookieStore.setItem(name, '');
@@ -2057,147 +2099,110 @@ const cookieStore = {
2057
2099
  return;
2058
2100
  }
2059
2101
  },
2060
-
2061
2102
  clear() {
2062
2103
  document.cookie = '';
2063
2104
  },
2064
-
2065
2105
  getAllKeys() {
2066
2106
  const ca = document.cookie.split(';');
2067
2107
  const keys = [];
2068
-
2069
2108
  for (let i = 0; i < ca.length; i++) {
2070
2109
  let c = ca[i];
2071
-
2072
2110
  while (c.charAt(0) == ' ') {
2073
2111
  c = c.substring(1, c.length);
2074
2112
  }
2075
-
2076
2113
  keys.push(c.split('=')[0]);
2077
2114
  }
2078
-
2079
2115
  return keys;
2080
2116
  }
2081
-
2082
2117
  };
2083
-
2084
2118
  const createStorageLike = store => {
2085
2119
  return {
2086
2120
  getItem(key) {
2087
2121
  return store.getItem(key);
2088
2122
  },
2089
-
2090
2123
  setItem(key, value) {
2091
2124
  store.setItem(key, value);
2092
2125
  },
2093
-
2094
2126
  removeItem(key) {
2095
2127
  store.removeItem(key);
2096
2128
  },
2097
-
2098
2129
  clear() {
2099
2130
  store.clear();
2100
2131
  },
2101
-
2102
2132
  getAllKeys() {
2103
2133
  const keys = [];
2104
-
2105
2134
  for (const key in localStorage) {
2106
2135
  keys.push(key);
2107
2136
  }
2108
-
2109
2137
  return keys;
2110
2138
  }
2111
-
2112
2139
  };
2113
2140
  };
2114
-
2115
2141
  const checkStoreIsSupported = (storage, key = '__mplssupport__') => {
2116
2142
  if (!window) {
2117
2143
  return false;
2118
2144
  }
2119
-
2120
2145
  try {
2121
2146
  const val = 'xyz';
2122
2147
  storage.setItem(key, val);
2123
-
2124
2148
  if (storage.getItem(key) !== val) {
2125
2149
  return false;
2126
2150
  }
2127
-
2128
2151
  storage.removeItem(key);
2129
2152
  return true;
2130
2153
  } catch (err) {
2131
2154
  return false;
2132
2155
  }
2133
2156
  };
2134
-
2135
2157
  let localStore = undefined;
2136
2158
  let sessionStore = undefined;
2137
-
2138
2159
  const createMemoryStorage = () => {
2139
2160
  const _cache = {};
2140
2161
  const store = {
2141
2162
  getItem(key) {
2142
2163
  return _cache[key];
2143
2164
  },
2144
-
2145
2165
  setItem(key, value) {
2146
2166
  _cache[key] = value !== null ? value : undefined;
2147
2167
  },
2148
-
2149
2168
  removeItem(key) {
2150
2169
  delete _cache[key];
2151
2170
  },
2152
-
2153
2171
  clear() {
2154
2172
  for (const key in _cache) {
2155
2173
  delete _cache[key];
2156
2174
  }
2157
2175
  },
2158
-
2159
2176
  getAllKeys() {
2160
2177
  const keys = [];
2161
-
2162
2178
  for (const key in _cache) {
2163
2179
  keys.push(key);
2164
2180
  }
2165
-
2166
2181
  return keys;
2167
2182
  }
2168
-
2169
2183
  };
2170
2184
  return store;
2171
2185
  };
2172
-
2173
2186
  const getStorage = (type, window) => {
2174
2187
  if (window) {
2175
- if (!localStorage) {
2188
+ if (!localStore) {
2176
2189
  const _localStore = createStorageLike(window.localStorage);
2177
-
2178
2190
  localStore = checkStoreIsSupported(_localStore) ? _localStore : undefined;
2179
2191
  }
2180
-
2181
2192
  if (!sessionStore) {
2182
2193
  const _sessionStore = createStorageLike(window.sessionStorage);
2183
-
2184
2194
  sessionStore = checkStoreIsSupported(_sessionStore) ? _sessionStore : undefined;
2185
2195
  }
2186
2196
  }
2187
-
2188
2197
  switch (type) {
2189
2198
  case 'cookie':
2190
2199
  return cookieStore || localStore || sessionStore || createMemoryStorage();
2191
-
2192
2200
  case 'localStorage':
2193
2201
  return localStore || sessionStore || createMemoryStorage();
2194
-
2195
2202
  case 'sessionStorage':
2196
2203
  return sessionStore || createMemoryStorage();
2197
-
2198
2204
  case 'memory':
2199
2205
  return createMemoryStorage();
2200
-
2201
2206
  default:
2202
2207
  return createMemoryStorage();
2203
2208
  }
@@ -2205,61 +2210,50 @@ const getStorage = (type, window) => {
2205
2210
 
2206
2211
  class PostHog extends PostHogCore {
2207
2212
  constructor(apiKey, options) {
2208
- super(apiKey, options); // posthog-js stores options in one object on
2209
-
2213
+ super(apiKey, options);
2214
+ // posthog-js stores options in one object on
2210
2215
  this._storageKey = options?.persistence_name ? `ph_${options.persistence_name}` : `ph_${apiKey}_posthog`;
2211
2216
  this._storage = getStorage(options?.persistence || 'localStorage', window);
2212
2217
  this.setupBootstrap(options);
2213
-
2214
2218
  if (options?.preloadFeatureFlags !== false) {
2215
2219
  this.reloadFeatureFlags();
2216
2220
  }
2217
2221
  }
2218
-
2219
2222
  getPersistedProperty(key) {
2220
2223
  if (!this._storageCache) {
2221
2224
  this._storageCache = JSON.parse(this._storage.getItem(this._storageKey) || '{}') || {};
2222
2225
  }
2223
-
2224
2226
  return this._storageCache[key];
2225
2227
  }
2226
-
2227
2228
  setPersistedProperty(key, value) {
2228
2229
  if (!this._storageCache) {
2229
2230
  this._storageCache = JSON.parse(this._storage.getItem(this._storageKey) || '{}') || {};
2230
2231
  }
2231
-
2232
2232
  if (value === null) {
2233
2233
  delete this._storageCache[key];
2234
2234
  } else {
2235
2235
  this._storageCache[key] = value;
2236
2236
  }
2237
-
2238
2237
  this._storage.setItem(this._storageKey, JSON.stringify(this._storageCache));
2239
2238
  }
2240
-
2241
2239
  fetch(url, options) {
2242
2240
  return window.fetch(url, options);
2243
2241
  }
2244
-
2245
2242
  getLibraryId() {
2246
2243
  return 'posthog-js-lite';
2247
2244
  }
2248
-
2249
2245
  getLibraryVersion() {
2250
2246
  return version;
2251
2247
  }
2252
-
2253
2248
  getCustomUserAgent() {
2254
2249
  return;
2255
2250
  }
2256
-
2257
2251
  getCommonEventProperties() {
2258
- return { ...super.getCommonEventProperties(),
2252
+ return {
2253
+ ...super.getCommonEventProperties(),
2259
2254
  ...getContext(window)
2260
2255
  };
2261
2256
  }
2262
-
2263
2257
  }
2264
2258
 
2265
2259
  exports.PostHog = PostHog;