posthog-js 1.200.0 → 1.200.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/all-external-dependencies.js +1 -1
  2. package/dist/all-external-dependencies.js.map +1 -1
  3. package/dist/array.full.es5.js +1 -1
  4. package/dist/array.full.es5.js.map +1 -1
  5. package/dist/array.full.js +1 -1
  6. package/dist/array.full.js.map +1 -1
  7. package/dist/array.full.no-external.js +1 -1
  8. package/dist/array.full.no-external.js.map +1 -1
  9. package/dist/array.js +1 -1
  10. package/dist/array.js.map +1 -1
  11. package/dist/array.no-external.js +1 -1
  12. package/dist/array.no-external.js.map +1 -1
  13. package/dist/customizations.full.js +1 -1
  14. package/dist/customizations.full.js.map +1 -1
  15. package/dist/dead-clicks-autocapture.js.map +1 -1
  16. package/dist/exception-autocapture.js.map +1 -1
  17. package/dist/external-scripts-loader.js.map +1 -1
  18. package/dist/main.js +1 -1
  19. package/dist/main.js.map +1 -1
  20. package/dist/module.d.ts +5 -0
  21. package/dist/module.full.d.ts +5 -0
  22. package/dist/module.full.js +1 -1
  23. package/dist/module.full.js.map +1 -1
  24. package/dist/module.full.no-external.d.ts +5 -0
  25. package/dist/module.full.no-external.js +1 -1
  26. package/dist/module.full.no-external.js.map +1 -1
  27. package/dist/module.js +1 -1
  28. package/dist/module.js.map +1 -1
  29. package/dist/module.no-external.d.ts +5 -0
  30. package/dist/module.no-external.js +1 -1
  31. package/dist/module.no-external.js.map +1 -1
  32. package/dist/recorder-v2.js.map +1 -1
  33. package/dist/recorder.js.map +1 -1
  34. package/dist/src/constants.d.ts +6 -0
  35. package/dist/src/entrypoints/tracing-headers.d.ts +2 -2
  36. package/dist/src/types.d.ts +5 -0
  37. package/dist/src/utils/globals.d.ts +2 -2
  38. package/dist/surveys-preview.js.map +1 -1
  39. package/dist/surveys.js.map +1 -1
  40. package/dist/tracing-headers.js +1 -1
  41. package/dist/tracing-headers.js.map +1 -1
  42. package/dist/web-vitals.js.map +1 -1
  43. package/lib/package.json +1 -1
  44. package/lib/src/constants.d.ts +6 -0
  45. package/lib/src/constants.js +6 -0
  46. package/lib/src/constants.js.map +1 -1
  47. package/lib/src/entrypoints/tracing-headers.d.ts +2 -2
  48. package/lib/src/entrypoints/tracing-headers.js +5 -3
  49. package/lib/src/entrypoints/tracing-headers.js.map +1 -1
  50. package/lib/src/extensions/replay/sessionrecording.js +3 -0
  51. package/lib/src/extensions/replay/sessionrecording.js.map +1 -1
  52. package/lib/src/extensions/tracing-headers.js +0 -1
  53. package/lib/src/extensions/tracing-headers.js.map +1 -1
  54. package/lib/src/posthog-core.js +36 -13
  55. package/lib/src/posthog-core.js.map +1 -1
  56. package/lib/src/sessionid.js +6 -0
  57. package/lib/src/sessionid.js.map +1 -1
  58. package/lib/src/types.d.ts +5 -0
  59. package/lib/src/types.js.map +1 -1
  60. package/lib/src/utils/globals.d.ts +2 -2
  61. package/lib/src/utils/globals.js.map +1 -1
  62. package/package.json +1 -1
@@ -33,6 +33,9 @@ var SessionIdManager = /** @class */ (function () {
33
33
  if (!instance.persistence) {
34
34
  throw new Error('SessionIdManager requires a PostHogPersistence instance');
35
35
  }
36
+ if (instance.config.__preview_experimental_cookieless_mode) {
37
+ throw new Error('SessionIdManager cannot be used with __preview_experimental_cookieless_mode');
38
+ }
36
39
  this.config = instance.config;
37
40
  this.persistence = instance.persistence;
38
41
  this._windowId = undefined;
@@ -187,6 +190,9 @@ var SessionIdManager = /** @class */ (function () {
187
190
  SessionIdManager.prototype.checkAndGetSessionAndWindowId = function (readOnly, _timestamp) {
188
191
  if (readOnly === void 0) { readOnly = false; }
189
192
  if (_timestamp === void 0) { _timestamp = null; }
193
+ if (this.config.__preview_experimental_cookieless_mode) {
194
+ throw new Error('checkAndGetSessionAndWindowId should not be called in __preview_experimental_cookieless_mode');
195
+ }
190
196
  var timestamp = _timestamp || new Date().getTime();
191
197
  // eslint-disable-next-line prefer-const
192
198
  var _a = __read(this._getSessionId(), 3), lastTimestamp = _a[0], sessionId = _a[1], startTimestamp = _a[2];
@@ -1 +1 @@
1
- {"version":3,"file":"sessionid.js","sourceRoot":"","sources":["../../src/sessionid.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AACA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA;AAExC,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AACrD,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAExC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAE7C,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AAGnD,IAAM,MAAM,GAAG,YAAY,CAAC,aAAa,CAAC,CAAA;AAE1C,MAAM,CAAC,IAAM,oCAAoC,GAAG,EAAE,GAAG,EAAE,CAAA,CAAC,aAAa;AACzE,MAAM,CAAC,IAAM,gCAAgC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAA,CAAC,WAAW;AACxE,IAAM,gCAAgC,GAAG,EAAE,CAAA,CAAC,WAAW;AACvD,IAAM,iCAAiC,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAA,CAAC,WAAW;AAEtE;IAeI,0BAAY,QAAiB,EAAE,kBAAiC,EAAE,iBAAgC;;QAH1F,8BAAyB,GAA+B,EAAE,CAAA;QAI9D,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC;YACxB,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAA;QAC9E,CAAC;QAED,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAA;QAC7B,IAAI,CAAC,WAAW,GAAG,QAAQ,CAAC,WAAW,CAAA;QACvC,IAAI,CAAC,SAAS,GAAG,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QACxB,CAAC;QAED,IAAM,YAAY,GAAG,aAAa,KAAK,CAAC,IAAI,CAAC,QAAQ,IAAI,wBAAwB,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,aAAa,CAAA;QAC7G,IAAM,qBAAqB,GAAG,cAAc,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,cAAc,CAAA;QAE1F,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAA;QAC3B,IAAI,CAAC,aAAa,CAAC,SAAS,EAAE,YAAY,EAAE,qBAAqB,CAAC,CAAA;QAElE,IAAI,aAAa,EAAE,CAAC;YAChB,IAAI,CAAC,yBAAyB,CAAC,OAAO,CAAC,UAAC,OAAO;gBAC3C,OAAA,OAAO,CACH,SAAS,EACT,QAAQ,EACR,aAAa,CAAC,CAAC,CAAC,EAAE,WAAW,aAAA,EAAE,eAAe,iBAAA,EAAE,wBAAwB,0BAAA,EAAE,CAAC,CAAC,CAAC,SAAS,CACzF;YAJD,CAIC,CACJ,CAAA;QACL,CAAC;QAED,OAAO;YACH,SAAS,WAAA;YACT,QAAQ,UAAA;YACR,qBAAqB,uBAAA;YACrB,YAAY,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,WAAW,aAAA,EAAE,eAAe,iBAAA,EAAE,wBAAwB,0BAAA,EAAE,CAAC,CAAC,CAAC,SAAS;YACpG,qBAAqB,EAAE,aAAa;SACvC,CAAA;IACL,CAAC;IACL,uBAAC;AAAD,CAAC,AA1PD,IA0PC","sourcesContent":["import { PostHogPersistence } from './posthog-persistence'\nimport { SESSION_ID } from './constants'\nimport { sessionStore } from './storage'\nimport { PostHogConfig, SessionIdChangedCallback } from './types'\nimport { uuid7ToTimestampMs, uuidv7 } from './uuidv7'\nimport { window } from './utils/globals'\n\nimport { isArray, isNumber, isUndefined } from './utils/type-utils'\nimport { createLogger } from './utils/logger'\n\nimport { clampToRange } from './utils/number-utils'\nimport { PostHog } from './posthog-core'\n\nconst logger = createLogger('[SessionId]')\n\nexport const DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS = 30 * 60 // 30 minutes\nexport const MAX_SESSION_IDLE_TIMEOUT_SECONDS = 10 * 60 * 60 // 10 hours\nconst MIN_SESSION_IDLE_TIMEOUT_SECONDS = 60 // 1 minute\nconst SESSION_LENGTH_LIMIT_MILLISECONDS = 24 * 3600 * 1000 // 24 hours\n\nexport class SessionIdManager {\n private readonly _sessionIdGenerator: () => string\n private readonly _windowIdGenerator: () => string\n private config: Partial<PostHogConfig>\n private persistence: PostHogPersistence\n private _windowId: string | null | undefined\n private _sessionId: string | null | undefined\n private readonly _window_id_storage_key: string\n private readonly _primary_window_exists_storage_key: string\n private _sessionStartTimestamp: number | null\n\n private _sessionActivityTimestamp: number | null\n private _sessionIdChangedHandlers: SessionIdChangedCallback[] = []\n private readonly _sessionTimeoutMs: number\n\n constructor(instance: PostHog, sessionIdGenerator?: () => string, windowIdGenerator?: () => string) {\n if (!instance.persistence) {\n throw new Error('SessionIdManager requires a PostHogPersistence instance')\n }\n\n this.config = instance.config\n this.persistence = instance.persistence\n this._windowId = undefined\n this._sessionId = undefined\n this._sessionStartTimestamp = null\n this._sessionActivityTimestamp = null\n this._sessionIdGenerator = sessionIdGenerator || uuidv7\n this._windowIdGenerator = windowIdGenerator || uuidv7\n\n const persistenceName = this.config['persistence_name'] || this.config['token']\n\n const desiredTimeout = this.config['session_idle_timeout_seconds'] || DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS\n this._sessionTimeoutMs =\n clampToRange(\n desiredTimeout,\n MIN_SESSION_IDLE_TIMEOUT_SECONDS,\n MAX_SESSION_IDLE_TIMEOUT_SECONDS,\n 'session_idle_timeout_seconds',\n DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS\n ) * 1000\n\n instance.register({ $configured_session_timeout_ms: this._sessionTimeoutMs })\n\n this._window_id_storage_key = 'ph_' + persistenceName + '_window_id'\n this._primary_window_exists_storage_key = 'ph_' + persistenceName + '_primary_window_exists'\n\n // primary_window_exists is set when the DOM has been loaded and is cleared on unload\n // if it exists here it means there was no unload which suggests this window is opened as a tab duplication, window.open, etc.\n if (this._canUseSessionStorage()) {\n const lastWindowId = sessionStore.parse(this._window_id_storage_key)\n\n const primaryWindowExists = sessionStore.parse(this._primary_window_exists_storage_key)\n if (lastWindowId && !primaryWindowExists) {\n // Persist window from previous storage state\n this._windowId = lastWindowId\n } else {\n // Wipe any reference to previous window id\n sessionStore.remove(this._window_id_storage_key)\n }\n // Flag this session as having a primary window\n sessionStore.set(this._primary_window_exists_storage_key, true)\n }\n\n if (this.config.bootstrap?.sessionID) {\n try {\n const sessionStartTimestamp = uuid7ToTimestampMs(this.config.bootstrap.sessionID)\n this._setSessionId(this.config.bootstrap.sessionID, new Date().getTime(), sessionStartTimestamp)\n } catch (e) {\n logger.error('Invalid sessionID in bootstrap', e)\n }\n }\n\n this._listenToReloadWindow()\n }\n\n get sessionTimeoutMs(): number {\n return this._sessionTimeoutMs\n }\n\n onSessionId(callback: SessionIdChangedCallback): () => void {\n // KLUDGE: when running in tests the handlers array was always undefined\n // it's yucky but safe to set it here so that it's always definitely available\n if (isUndefined(this._sessionIdChangedHandlers)) {\n this._sessionIdChangedHandlers = []\n }\n\n this._sessionIdChangedHandlers.push(callback)\n if (this._sessionId) {\n callback(this._sessionId, this._windowId)\n }\n return () => {\n this._sessionIdChangedHandlers = this._sessionIdChangedHandlers.filter((h) => h !== callback)\n }\n }\n\n private _canUseSessionStorage(): boolean {\n // We only want to use sessionStorage if persistence is enabled and not memory storage\n return this.config.persistence !== 'memory' && !this.persistence.disabled && sessionStore.is_supported()\n }\n\n // Note: this tries to store the windowId in sessionStorage. SessionStorage is unique to the current window/tab,\n // and persists page loads/reloads. So it's uniquely suited for storing the windowId. This function also respects\n // when persistence is disabled (by user config) and when sessionStorage is not supported (it *should* be supported on all browsers),\n // and in that case, it falls back to memory (which sadly, won't persist page loads)\n private _setWindowId(windowId: string): void {\n if (windowId !== this._windowId) {\n this._windowId = windowId\n if (this._canUseSessionStorage()) {\n sessionStore.set(this._window_id_storage_key, windowId)\n }\n }\n }\n\n private _getWindowId(): string | null {\n if (this._windowId) {\n return this._windowId\n }\n if (this._canUseSessionStorage()) {\n return sessionStore.parse(this._window_id_storage_key)\n }\n // New window id will be generated\n return null\n }\n\n // Note: 'this.persistence.register' can be disabled in the config.\n // In that case, this works by storing sessionId and the timestamp in memory.\n private _setSessionId(\n sessionId: string | null,\n sessionActivityTimestamp: number | null,\n sessionStartTimestamp: number | null\n ): void {\n if (\n sessionId !== this._sessionId ||\n sessionActivityTimestamp !== this._sessionActivityTimestamp ||\n sessionStartTimestamp !== this._sessionStartTimestamp\n ) {\n this._sessionStartTimestamp = sessionStartTimestamp\n this._sessionActivityTimestamp = sessionActivityTimestamp\n this._sessionId = sessionId\n\n this.persistence.register({\n [SESSION_ID]: [sessionActivityTimestamp, sessionId, sessionStartTimestamp],\n })\n }\n }\n\n private _getSessionId(): [number, string, number] {\n if (this._sessionId && this._sessionActivityTimestamp && this._sessionStartTimestamp) {\n return [this._sessionActivityTimestamp, this._sessionId, this._sessionStartTimestamp]\n }\n const sessionId = this.persistence.props[SESSION_ID]\n\n if (isArray(sessionId) && sessionId.length === 2) {\n // Storage does not yet have a session start time. Add the last activity timestamp as the start time\n sessionId.push(sessionId[0])\n }\n\n return sessionId || [0, null, 0]\n }\n\n // Resets the session id by setting it to null. On the subsequent call to checkAndGetSessionAndWindowId,\n // new ids will be generated.\n resetSessionId(): void {\n this._setSessionId(null, null, null)\n }\n\n /*\n * Listens to window unloads and removes the primaryWindowExists key from sessionStorage.\n * Reloaded or fresh tabs created after a DOM unloads (reloading the same tab) WILL NOT have this primaryWindowExists flag in session storage.\n * Cloned sessions (new tab, tab duplication, window.open(), ...) WILL have this primaryWindowExists flag in their copied session storage.\n * We conditionally check the primaryWindowExists value in the constructor to decide if the window id in the last session storage should be carried over.\n */\n private _listenToReloadWindow(): void {\n window?.addEventListener('beforeunload', () => {\n if (this._canUseSessionStorage()) {\n sessionStore.remove(this._primary_window_exists_storage_key)\n }\n })\n }\n\n /*\n * This function returns the current sessionId and windowId. It should be used to\n * access these values over directly calling `._sessionId` or `._windowId`.\n * In addition to returning the sessionId and windowId, this function also manages cycling the\n * sessionId and windowId when appropriate by doing the following:\n *\n * 1. If the sessionId or windowId is not set, it will generate a new one and store it.\n * 2. If the readOnly param is set to false, it will:\n * a. Check if it has been > SESSION_CHANGE_THRESHOLD since the last call with this flag set.\n * If so, it will generate a new sessionId and store it.\n * b. Update the timestamp stored with the sessionId to ensure the current session is extended\n * for the appropriate amount of time.\n *\n * @param {boolean} readOnly (optional) Defaults to False. Should be set to True when the call to the function should not extend or cycle the session (e.g. being called for non-user generated events)\n * @param {Number} timestamp (optional) Defaults to the current time. The timestamp to be stored with the sessionId (used when determining if a new sessionId should be generated)\n */\n checkAndGetSessionAndWindowId(readOnly = false, _timestamp: number | null = null) {\n const timestamp = _timestamp || new Date().getTime()\n\n // eslint-disable-next-line prefer-const\n let [lastTimestamp, sessionId, startTimestamp] = this._getSessionId()\n let windowId = this._getWindowId()\n\n const sessionPastMaximumLength =\n isNumber(startTimestamp) &&\n startTimestamp > 0 &&\n Math.abs(timestamp - startTimestamp) > SESSION_LENGTH_LIMIT_MILLISECONDS\n\n let valuesChanged = false\n const noSessionId = !sessionId\n const activityTimeout = !readOnly && Math.abs(timestamp - lastTimestamp) > this.sessionTimeoutMs\n if (noSessionId || activityTimeout || sessionPastMaximumLength) {\n sessionId = this._sessionIdGenerator()\n windowId = this._windowIdGenerator()\n logger.info('new session ID generated', {\n sessionId,\n windowId,\n changeReason: { noSessionId, activityTimeout, sessionPastMaximumLength },\n })\n startTimestamp = timestamp\n valuesChanged = true\n } else if (!windowId) {\n windowId = this._windowIdGenerator()\n valuesChanged = true\n }\n\n const newTimestamp = lastTimestamp === 0 || !readOnly || sessionPastMaximumLength ? timestamp : lastTimestamp\n const sessionStartTimestamp = startTimestamp === 0 ? new Date().getTime() : startTimestamp\n\n this._setWindowId(windowId)\n this._setSessionId(sessionId, newTimestamp, sessionStartTimestamp)\n\n if (valuesChanged) {\n this._sessionIdChangedHandlers.forEach((handler) =>\n handler(\n sessionId,\n windowId,\n valuesChanged ? { noSessionId, activityTimeout, sessionPastMaximumLength } : undefined\n )\n )\n }\n\n return {\n sessionId,\n windowId,\n sessionStartTimestamp,\n changeReason: valuesChanged ? { noSessionId, activityTimeout, sessionPastMaximumLength } : undefined,\n lastActivityTimestamp: lastTimestamp,\n }\n }\n}\n"]}
1
+ {"version":3,"file":"sessionid.js","sourceRoot":"","sources":["../../src/sessionid.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AACA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA;AAExC,OAAO,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AACrD,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAExC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAE7C,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AAGnD,IAAM,MAAM,GAAG,YAAY,CAAC,aAAa,CAAC,CAAA;AAE1C,MAAM,CAAC,IAAM,oCAAoC,GAAG,EAAE,GAAG,EAAE,CAAA,CAAC,aAAa;AACzE,MAAM,CAAC,IAAM,gCAAgC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAA,CAAC,WAAW;AACxE,IAAM,gCAAgC,GAAG,EAAE,CAAA,CAAC,WAAW;AACvD,IAAM,iCAAiC,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAA,CAAC,WAAW;AAEtE;IAeI,0BAAY,QAAiB,EAAE,kBAAiC,EAAE,iBAAgC;;QAH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A;YACT,QAAQ,UAAA;YACR,qBAAqB,uBAAA;YACrB,YAAY,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,WAAW,aAAA,EAAE,eAAe,iBAAA,EAAE,wBAAwB,0BAAA,EAAE,CAAC,CAAC,CAAC,SAAS;YACpG,qBAAqB,EAAE,aAAa;SACvC,CAAA;IACL,CAAC;IACL,uBAAC;AAAD,CAAC,AAlQD,IAkQC","sourcesContent":["import { PostHogPersistence } from './posthog-persistence'\nimport { SESSION_ID } from './constants'\nimport { sessionStore } from './storage'\nimport { PostHogConfig, SessionIdChangedCallback } from './types'\nimport { uuid7ToTimestampMs, uuidv7 } from './uuidv7'\nimport { window } from './utils/globals'\n\nimport { isArray, isNumber, isUndefined } from './utils/type-utils'\nimport { createLogger } from './utils/logger'\n\nimport { clampToRange } from './utils/number-utils'\nimport { PostHog } from './posthog-core'\n\nconst logger = createLogger('[SessionId]')\n\nexport const DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS = 30 * 60 // 30 minutes\nexport const MAX_SESSION_IDLE_TIMEOUT_SECONDS = 10 * 60 * 60 // 10 hours\nconst MIN_SESSION_IDLE_TIMEOUT_SECONDS = 60 // 1 minute\nconst SESSION_LENGTH_LIMIT_MILLISECONDS = 24 * 3600 * 1000 // 24 hours\n\nexport class SessionIdManager {\n private readonly _sessionIdGenerator: () => string\n private readonly _windowIdGenerator: () => string\n private config: Partial<PostHogConfig>\n private persistence: PostHogPersistence\n private _windowId: string | null | undefined\n private _sessionId: string | null | undefined\n private readonly _window_id_storage_key: string\n private readonly _primary_window_exists_storage_key: string\n private _sessionStartTimestamp: number | null\n\n private _sessionActivityTimestamp: number | null\n private _sessionIdChangedHandlers: SessionIdChangedCallback[] = []\n private readonly _sessionTimeoutMs: number\n\n constructor(instance: PostHog, sessionIdGenerator?: () => string, windowIdGenerator?: () => string) {\n if (!instance.persistence) {\n throw new Error('SessionIdManager requires a PostHogPersistence instance')\n }\n if (instance.config.__preview_experimental_cookieless_mode) {\n throw new Error('SessionIdManager cannot be used with __preview_experimental_cookieless_mode')\n }\n\n this.config = instance.config\n this.persistence = instance.persistence\n this._windowId = undefined\n this._sessionId = undefined\n this._sessionStartTimestamp = null\n this._sessionActivityTimestamp = null\n this._sessionIdGenerator = sessionIdGenerator || uuidv7\n this._windowIdGenerator = windowIdGenerator || uuidv7\n\n const persistenceName = this.config['persistence_name'] || this.config['token']\n\n const desiredTimeout = this.config['session_idle_timeout_seconds'] || DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS\n this._sessionTimeoutMs =\n clampToRange(\n desiredTimeout,\n MIN_SESSION_IDLE_TIMEOUT_SECONDS,\n MAX_SESSION_IDLE_TIMEOUT_SECONDS,\n 'session_idle_timeout_seconds',\n DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS\n ) * 1000\n\n instance.register({ $configured_session_timeout_ms: this._sessionTimeoutMs })\n\n this._window_id_storage_key = 'ph_' + persistenceName + '_window_id'\n this._primary_window_exists_storage_key = 'ph_' + persistenceName + '_primary_window_exists'\n\n // primary_window_exists is set when the DOM has been loaded and is cleared on unload\n // if it exists here it means there was no unload which suggests this window is opened as a tab duplication, window.open, etc.\n if (this._canUseSessionStorage()) {\n const lastWindowId = sessionStore.parse(this._window_id_storage_key)\n\n const primaryWindowExists = sessionStore.parse(this._primary_window_exists_storage_key)\n if (lastWindowId && !primaryWindowExists) {\n // Persist window from previous storage state\n this._windowId = lastWindowId\n } else {\n // Wipe any reference to previous window id\n sessionStore.remove(this._window_id_storage_key)\n }\n // Flag this session as having a primary window\n sessionStore.set(this._primary_window_exists_storage_key, true)\n }\n\n if (this.config.bootstrap?.sessionID) {\n try {\n const sessionStartTimestamp = uuid7ToTimestampMs(this.config.bootstrap.sessionID)\n this._setSessionId(this.config.bootstrap.sessionID, new Date().getTime(), sessionStartTimestamp)\n } catch (e) {\n logger.error('Invalid sessionID in bootstrap', e)\n }\n }\n\n this._listenToReloadWindow()\n }\n\n get sessionTimeoutMs(): number {\n return this._sessionTimeoutMs\n }\n\n onSessionId(callback: SessionIdChangedCallback): () => void {\n // KLUDGE: when running in tests the handlers array was always undefined\n // it's yucky but safe to set it here so that it's always definitely available\n if (isUndefined(this._sessionIdChangedHandlers)) {\n this._sessionIdChangedHandlers = []\n }\n\n this._sessionIdChangedHandlers.push(callback)\n if (this._sessionId) {\n callback(this._sessionId, this._windowId)\n }\n return () => {\n this._sessionIdChangedHandlers = this._sessionIdChangedHandlers.filter((h) => h !== callback)\n }\n }\n\n private _canUseSessionStorage(): boolean {\n // We only want to use sessionStorage if persistence is enabled and not memory storage\n return this.config.persistence !== 'memory' && !this.persistence.disabled && sessionStore.is_supported()\n }\n\n // Note: this tries to store the windowId in sessionStorage. SessionStorage is unique to the current window/tab,\n // and persists page loads/reloads. So it's uniquely suited for storing the windowId. This function also respects\n // when persistence is disabled (by user config) and when sessionStorage is not supported (it *should* be supported on all browsers),\n // and in that case, it falls back to memory (which sadly, won't persist page loads)\n private _setWindowId(windowId: string): void {\n if (windowId !== this._windowId) {\n this._windowId = windowId\n if (this._canUseSessionStorage()) {\n sessionStore.set(this._window_id_storage_key, windowId)\n }\n }\n }\n\n private _getWindowId(): string | null {\n if (this._windowId) {\n return this._windowId\n }\n if (this._canUseSessionStorage()) {\n return sessionStore.parse(this._window_id_storage_key)\n }\n // New window id will be generated\n return null\n }\n\n // Note: 'this.persistence.register' can be disabled in the config.\n // In that case, this works by storing sessionId and the timestamp in memory.\n private _setSessionId(\n sessionId: string | null,\n sessionActivityTimestamp: number | null,\n sessionStartTimestamp: number | null\n ): void {\n if (\n sessionId !== this._sessionId ||\n sessionActivityTimestamp !== this._sessionActivityTimestamp ||\n sessionStartTimestamp !== this._sessionStartTimestamp\n ) {\n this._sessionStartTimestamp = sessionStartTimestamp\n this._sessionActivityTimestamp = sessionActivityTimestamp\n this._sessionId = sessionId\n\n this.persistence.register({\n [SESSION_ID]: [sessionActivityTimestamp, sessionId, sessionStartTimestamp],\n })\n }\n }\n\n private _getSessionId(): [number, string, number] {\n if (this._sessionId && this._sessionActivityTimestamp && this._sessionStartTimestamp) {\n return [this._sessionActivityTimestamp, this._sessionId, this._sessionStartTimestamp]\n }\n const sessionId = this.persistence.props[SESSION_ID]\n\n if (isArray(sessionId) && sessionId.length === 2) {\n // Storage does not yet have a session start time. Add the last activity timestamp as the start time\n sessionId.push(sessionId[0])\n }\n\n return sessionId || [0, null, 0]\n }\n\n // Resets the session id by setting it to null. On the subsequent call to checkAndGetSessionAndWindowId,\n // new ids will be generated.\n resetSessionId(): void {\n this._setSessionId(null, null, null)\n }\n\n /*\n * Listens to window unloads and removes the primaryWindowExists key from sessionStorage.\n * Reloaded or fresh tabs created after a DOM unloads (reloading the same tab) WILL NOT have this primaryWindowExists flag in session storage.\n * Cloned sessions (new tab, tab duplication, window.open(), ...) WILL have this primaryWindowExists flag in their copied session storage.\n * We conditionally check the primaryWindowExists value in the constructor to decide if the window id in the last session storage should be carried over.\n */\n private _listenToReloadWindow(): void {\n window?.addEventListener('beforeunload', () => {\n if (this._canUseSessionStorage()) {\n sessionStore.remove(this._primary_window_exists_storage_key)\n }\n })\n }\n\n /*\n * This function returns the current sessionId and windowId. It should be used to\n * access these values over directly calling `._sessionId` or `._windowId`.\n * In addition to returning the sessionId and windowId, this function also manages cycling the\n * sessionId and windowId when appropriate by doing the following:\n *\n * 1. If the sessionId or windowId is not set, it will generate a new one and store it.\n * 2. If the readOnly param is set to false, it will:\n * a. Check if it has been > SESSION_CHANGE_THRESHOLD since the last call with this flag set.\n * If so, it will generate a new sessionId and store it.\n * b. Update the timestamp stored with the sessionId to ensure the current session is extended\n * for the appropriate amount of time.\n *\n * @param {boolean} readOnly (optional) Defaults to False. Should be set to True when the call to the function should not extend or cycle the session (e.g. being called for non-user generated events)\n * @param {Number} timestamp (optional) Defaults to the current time. The timestamp to be stored with the sessionId (used when determining if a new sessionId should be generated)\n */\n checkAndGetSessionAndWindowId(readOnly = false, _timestamp: number | null = null) {\n if (this.config.__preview_experimental_cookieless_mode) {\n throw new Error(\n 'checkAndGetSessionAndWindowId should not be called in __preview_experimental_cookieless_mode'\n )\n }\n const timestamp = _timestamp || new Date().getTime()\n\n // eslint-disable-next-line prefer-const\n let [lastTimestamp, sessionId, startTimestamp] = this._getSessionId()\n let windowId = this._getWindowId()\n\n const sessionPastMaximumLength =\n isNumber(startTimestamp) &&\n startTimestamp > 0 &&\n Math.abs(timestamp - startTimestamp) > SESSION_LENGTH_LIMIT_MILLISECONDS\n\n let valuesChanged = false\n const noSessionId = !sessionId\n const activityTimeout = !readOnly && Math.abs(timestamp - lastTimestamp) > this.sessionTimeoutMs\n if (noSessionId || activityTimeout || sessionPastMaximumLength) {\n sessionId = this._sessionIdGenerator()\n windowId = this._windowIdGenerator()\n logger.info('new session ID generated', {\n sessionId,\n windowId,\n changeReason: { noSessionId, activityTimeout, sessionPastMaximumLength },\n })\n startTimestamp = timestamp\n valuesChanged = true\n } else if (!windowId) {\n windowId = this._windowIdGenerator()\n valuesChanged = true\n }\n\n const newTimestamp = lastTimestamp === 0 || !readOnly || sessionPastMaximumLength ? timestamp : lastTimestamp\n const sessionStartTimestamp = startTimestamp === 0 ? new Date().getTime() : startTimestamp\n\n this._setWindowId(windowId)\n this._setSessionId(sessionId, newTimestamp, sessionStartTimestamp)\n\n if (valuesChanged) {\n this._sessionIdChangedHandlers.forEach((handler) =>\n handler(\n sessionId,\n windowId,\n valuesChanged ? { noSessionId, activityTimeout, sessionPastMaximumLength } : undefined\n )\n )\n }\n\n return {\n sessionId,\n windowId,\n sessionStartTimestamp,\n changeReason: valuesChanged ? { noSessionId, activityTimeout, sessionPastMaximumLength } : undefined,\n lastActivityTimestamp: lastTimestamp,\n }\n }\n}\n"]}
@@ -281,6 +281,11 @@ export interface PostHogConfig {
281
281
  * enables the new RemoteConfig approach to loading config instead of decide
282
282
  * */
283
283
  __preview_remote_config?: boolean;
284
+ /**
285
+ * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION
286
+ * whether to send a sentinel value for distinct id, device id, and session id, which will be replaced server-side by a cookieless hash
287
+ * */
288
+ __preview_experimental_cookieless_mode?: boolean;
284
289
  }
285
290
  export interface OptInOutCapturingOptions {
286
291
  capture: (event: string, properties: Properties, options: CaptureOptions) => void;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAOA,MAAM,CAAC,IAAM,sBAAsB,GAAG,mBAAmB,CAAA;AAEzD,MAAM,CAAC,IAAM,wBAAwB,GAAG;IACpC,WAAW;IACX,WAAW;IACX,YAAY;IACZ,MAAM;IACN,kBAAkB;IAClB,aAAa;IACb,cAAc;IACd,WAAW;IACX,gBAAgB;IAChB,eAAe;IACf,4BAA4B;IAC5B,yBAAyB;IACzB,4BAA4B;IAC5B,sBAAsB;CAChB,CAAA;AA2ZV,MAAM,CAAN,IAAY,WAGX;AAHD,WAAY,WAAW;IACnB,iCAAkB,CAAA;IAClB,gCAAiB,CAAA;AACrB,CAAC,EAHW,WAAW,KAAX,WAAW,QAGtB;AAyUD,2EAA2E;AAC3E,yEAAyE;AACzE,iFAAiF;AACjF,MAAM,CAAC,IAAM,cAAc,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAU,CAAA","sourcesContent":["import { PostHog } from './posthog-core'\nimport type { SegmentAnalytics } from './extensions/segment-integration'\nimport { recordOptions } from './extensions/replay/sessionrecording-utils'\n\nexport type Property = any\nexport type Properties = Record<string, Property>\n\nexport const COPY_AUTOCAPTURE_EVENT = '$copy_autocapture'\n\nexport const knownUnsafeEditableEvent = [\n '$snapshot',\n '$pageview',\n '$pageleave',\n '$set',\n 'survey dismissed',\n 'survey sent',\n 'survey shown',\n '$identify',\n '$groupidentify',\n '$create_alias',\n '$$client_ingestion_warning',\n '$web_experiment_applied',\n '$feature_enrollment_update',\n '$feature_flag_called',\n] as const\n\n/**\n * These events can be processed by the `beforeCapture` function\n * but can cause unexpected confusion in data.\n *\n * Some features of PostHog rely on receiving 100% of these events\n */\nexport type KnownUnsafeEditableEvent = typeof knownUnsafeEditableEvent[number]\n\n/**\n * These are known events PostHog events that can be processed by the `beforeCapture` function\n * That means PostHog functionality does not rely on receiving 100% of these for calculations\n * So, it is safe to sample them to reduce the volume of events sent to PostHog\n */\nexport type KnownEventName =\n | '$heatmaps_data'\n | '$opt_in'\n | '$exception'\n | '$$heatmap'\n | '$web_vitals'\n | '$dead_click'\n | '$autocapture'\n | typeof COPY_AUTOCAPTURE_EVENT\n | '$rageclick'\n\nexport type EventName =\n | KnownUnsafeEditableEvent\n | KnownEventName\n // magic value so that the type of EventName is a set of known strings or any other string\n // which means you get autocomplete for known strings\n // but no type complaints when you add an arbitrary string\n | (string & {})\n\nexport interface CaptureResult {\n uuid: string\n event: EventName\n properties: Properties\n $set?: Properties\n $set_once?: Properties\n timestamp?: Date\n}\n\nexport type AutocaptureCompatibleElement = 'a' | 'button' | 'form' | 'input' | 'select' | 'textarea' | 'label'\nexport type DomAutocaptureEvents = 'click' | 'change' | 'submit'\n\n/**\n * If an array is passed for an allowlist, autocapture events will only be sent for elements matching\n * at least one of the elements in the array. Multiple allowlists can be used\n */\nexport interface AutocaptureConfig {\n /**\n * List of URLs to allow autocapture on, can be strings to match\n * or regexes e.g. ['https://example.com', 'test.com/.*']\n * this is useful when you want to autocapture on specific pages only\n *\n * if you set both url_allowlist and url_ignorelist,\n * we check the allowlist first and then the ignorelist.\n * the ignorelist can override the allowlist\n */\n url_allowlist?: (string | RegExp)[]\n\n /**\n * List of URLs to not allow autocapture on, can be strings to match\n * or regexes e.g. ['https://example.com', 'test.com/.*']\n * this is useful when you want to autocapture on most pages but not some specific ones\n *\n * if you set both url_allowlist and url_ignorelist,\n * we check the allowlist first and then the ignorelist.\n * the ignorelist can override the allowlist\n */\n url_ignorelist?: (string | RegExp)[]\n\n /**\n * List of DOM events to allow autocapture on e.g. ['click', 'change', 'submit']\n */\n dom_event_allowlist?: DomAutocaptureEvents[]\n\n /**\n * List of DOM elements to allow autocapture on\n * e.g. ['a', 'button', 'form', 'input', 'select', 'textarea', 'label']\n * we consider the tree of elements from the root to the target element of the click event\n * so for the tree div > div > button > svg\n * if the allowlist has button then we allow the capture when the button or the svg is the click target\n * but not if either of the divs are detected as the click target\n */\n element_allowlist?: AutocaptureCompatibleElement[]\n\n /**\n * List of CSS selectors to allow autocapture on\n * e.g. ['[ph-capture]']\n * we consider the tree of elements from the root to the target element of the click event\n * so for the tree div > div > button > svg\n * and allow list config `['[id]']`\n * we will capture the click if the click-target or its parents has any id\n */\n css_selector_allowlist?: string[]\n\n /**\n * Exclude certain element attributes from autocapture\n * E.g. ['aria-label'] or [data-attr-pii]\n */\n element_attribute_ignorelist?: string[]\n\n capture_copied_text?: boolean\n}\n\nexport interface BootstrapConfig {\n distinctID?: string\n isIdentifiedID?: boolean\n featureFlags?: Record<string, boolean | string>\n featureFlagPayloads?: Record<string, JsonType>\n /**\n * Optionally provide a sessionID, this is so that you can provide an existing sessionID here to continue a user's session across a domain or device. It MUST be:\n * - unique to this user\n * - a valid UUID v7\n * - the timestamp part must be <= the timestamp of the first event in the session\n * - the timestamp of the last event in the session must be < the timestamp part + 24 hours\n * **/\n sessionID?: string\n}\n\nexport type SupportedWebVitalsMetrics = 'LCP' | 'CLS' | 'FCP' | 'INP'\n\nexport interface PerformanceCaptureConfig {\n /** works with session replay to use the browser's native performance observer to capture performance metrics */\n network_timing?: boolean\n /** use chrome's web vitals library to wrap fetch and capture web vitals */\n web_vitals?: boolean\n /**\n * We observe very large values reported by the Chrome web vitals library\n * These outliers are likely not real, useful values, and we exclude them\n * You can set this to 0 in order to include all values, NB this is not recommended\n * if not set this defaults to 15 minutes\n */\n __web_vitals_max_value?: number\n /**\n * By default all 4 metrics are captured\n * You can set this config to restrict which metrics are captured\n * e.g. ['CLS', 'FCP'] to only capture those two metrics\n * NB setting this does not override whether the capture is enabled\n */\n web_vitals_allowed_metrics?: SupportedWebVitalsMetrics[]\n /**\n * we delay flushing web vitals metrics to reduce the number of events we send\n * this is the maximum time we will wait before sending the metrics\n * if not set it defaults to 5 seconds\n */\n web_vitals_delayed_flush_ms?: number\n}\n\nexport interface DeadClickCandidate {\n node: Element\n originalEvent: MouseEvent\n timestamp: number\n // time between click and the most recent scroll\n scrollDelayMs?: number\n // time between click and the most recent mutation\n mutationDelayMs?: number\n // time between click and the most recent selection changed event\n selectionChangedDelayMs?: number\n // if neither scroll nor mutation seen before threshold passed\n absoluteDelayMs?: number\n}\n\nexport type DeadClicksAutoCaptureConfig = {\n // by default if a click is followed by a sroll within 100ms it is not a dead click\n scroll_threshold_ms?: number\n // by default if a click is followed by a selection change within 100ms it is not a dead click\n selection_change_threshold_ms?: number\n // by default if a click is followed by a mutation within 2500ms it is not a dead click\n mutation_threshold_ms?: number\n /**\n * Allows setting behavior for when a dead click is captured.\n * For e.g. to support capture to heatmaps\n *\n * If not provided the default behavior is to auto-capture dead click events\n *\n * Only intended to be provided by the SDK\n */\n __onCapture?: ((click: DeadClickCandidate, properties: Properties) => void) | undefined\n} & Pick<AutocaptureConfig, 'element_attribute_ignorelist'>\n\nexport interface HeatmapConfig {\n /*\n * how often to send batched data in $$heatmap_data events\n * if set to 0 or not set, sends using the default interval of 1 second\n * */\n flush_interval_milliseconds: number\n}\n\nexport type BeforeSendFn = (cr: CaptureResult | null) => CaptureResult | null\n\nexport interface PostHogConfig {\n api_host: string\n /** @deprecated - This property is no longer supported */\n api_method?: string\n api_transport?: 'XHR' | 'fetch'\n ui_host: string | null\n token: string\n autocapture: boolean | AutocaptureConfig\n rageclick: boolean\n cross_subdomain_cookie: boolean\n persistence: 'localStorage' | 'cookie' | 'memory' | 'localStorage+cookie' | 'sessionStorage'\n persistence_name: string\n /** @deprecated - Use 'persistence_name' instead */\n cookie_name?: string\n loaded: (posthog_instance: PostHog) => void\n store_google: boolean\n custom_campaign_params: string[]\n // a list of strings to be tested against navigator.userAgent to determine if the source is a bot\n // this is **added to** the default list of bots that we check\n // defaults to the empty array\n custom_blocked_useragents: string[]\n save_referrer: boolean\n verbose: boolean\n capture_pageview: boolean\n capture_pageleave: boolean | 'if_capture_pageview'\n debug: boolean\n cookie_expiration: number\n upgrade: boolean\n disable_session_recording: boolean\n disable_persistence: boolean\n /** @deprecated - use `disable_persistence` instead */\n disable_cookie?: boolean\n disable_surveys: boolean\n disable_web_experiments: boolean\n /** If set, posthog-js will never load external scripts such as those needed for Session Replay or Surveys. */\n disable_external_dependency_loading?: boolean\n enable_recording_console_log?: boolean\n secure_cookie: boolean\n ip: boolean\n /** Starts the SDK in an opted out state requiring opt_in_capturing() to be called before events will b captured */\n opt_out_capturing_by_default: boolean\n opt_out_capturing_persistence_type: 'localStorage' | 'cookie'\n /** If set to true this will disable persistence if the user is opted out of capturing. @default false */\n opt_out_persistence_by_default?: boolean\n /** Opt out of user agent filtering such as googlebot or other bots. Defaults to `false` */\n opt_out_useragent_filter: boolean\n\n opt_out_capturing_cookie_prefix: string | null\n opt_in_site_apps: boolean\n respect_dnt: boolean\n /** @deprecated - use `property_denylist` instead */\n property_blacklist?: string[]\n property_denylist: string[]\n request_headers: { [header_name: string]: string }\n on_request_error?: (error: RequestResponse) => void\n /** @deprecated - use `request_headers` instead */\n xhr_headers?: { [header_name: string]: string }\n /** @deprecated - use `on_request_error` instead */\n on_xhr_error?: (failedRequest: XMLHttpRequest) => void\n inapp_protocol: string\n inapp_link_new_window: boolean\n request_batching: boolean\n sanitize_properties: ((properties: Properties, event_name: string) => Properties) | null\n properties_string_max_length: number\n session_recording: SessionRecordingOptions\n session_idle_timeout_seconds: number\n mask_all_element_attributes: boolean\n mask_all_text: boolean\n advanced_disable_decide: boolean\n advanced_disable_feature_flags: boolean\n advanced_disable_feature_flags_on_first_load: boolean\n advanced_disable_toolbar_metrics: boolean\n feature_flag_request_timeout_ms: number\n get_device_id: (uuid: string) => string\n name: string\n /**\n * this is a read-only function that can be used to react to event capture\n * @deprecated - use `before_send` instead - NB before_send is not read only\n */\n _onCapture: (eventName: string, eventData: CaptureResult) => void\n /**\n * This function or array of functions - if provided - are called immediately before sending data to the server.\n * It allows you to edit data before it is sent, or choose not to send it all.\n * if provided as an array the functions are called in the order they are provided\n * any one function returning null means the event will not be sent\n */\n before_send?: BeforeSendFn | BeforeSendFn[]\n capture_performance?: boolean | PerformanceCaptureConfig\n // Should only be used for testing. Could negatively impact performance.\n disable_compression: boolean\n bootstrap: BootstrapConfig\n segment?: SegmentAnalytics\n __preview_send_client_session_params?: boolean\n /* @deprecated - use `capture_heatmaps` instead */\n enable_heatmaps?: boolean\n capture_heatmaps?: boolean | HeatmapConfig\n capture_dead_clicks?: boolean | DeadClicksAutoCaptureConfig\n disable_scroll_properties?: boolean\n // Let the pageview scroll stats use a custom css selector for the root element, e.g. `main`\n scroll_root_selector?: string | string[]\n\n /** You can control whether events from PostHog-js have person processing enabled with the `person_profiles` config setting. There are three options:\n * - `person_profiles: 'always'` _(default)_ - we will process persons data for all events\n * - `person_profiles: 'never'` - we won't process persons for any event. This means that anonymous users will not be merged once they sign up or login, so you lose the ability to create funnels that track users from anonymous to identified. All events (including `$identify`) will be sent with `$process_person_profile: False`.\n * - `person_profiles: 'identified_only'` - we will only process persons when you call `posthog.identify`, `posthog.alias`, `posthog.setPersonProperties`, `posthog.group`, `posthog.setPersonPropertiesForFlags` or `posthog.setGroupPropertiesForFlags` Anonymous users won't get person profiles.\n */\n person_profiles?: 'always' | 'never' | 'identified_only'\n /** @deprecated - use `person_profiles` instead */\n process_person?: 'always' | 'never' | 'identified_only'\n\n /** Client side rate limiting */\n rate_limiting?: {\n /** The average number of events per second that should be permitted (defaults to 10) */\n events_per_second?: number\n /** How many events can be captured in a burst. This defaults to 10 times the events_per_second count */\n events_burst_limit?: number\n }\n\n /** Used when sending data via `fetch`, use with care, this is intentionally meant to be used with NextJS `fetch`\n * Incorrect usage may cause out-of-date data for feature flags, actions tracking, etc.\n * See https://nextjs.org/docs/app/api-reference/functions/fetch#fetchurl-options\n */\n fetch_options?: {\n cache?: RequestInit['cache']\n next_options?: NextOptions\n }\n\n /**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * whether to wrap fetch and add tracing headers to the request\n * */\n __add_tracing_headers?: boolean\n\n /**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * enables the new RemoteConfig approach to loading config instead of decide\n * */\n __preview_remote_config?: boolean\n}\n\nexport interface OptInOutCapturingOptions {\n capture: (event: string, properties: Properties, options: CaptureOptions) => void\n capture_event_name: string\n capture_properties: Properties\n enable_persistence: boolean\n clear_persistence: boolean\n persistence_type: 'cookie' | 'localStorage' | 'localStorage+cookie'\n cookie_prefix: string\n cookie_expiration: number\n cross_subdomain_cookie: boolean\n secure_cookie: boolean\n}\n\nexport interface IsFeatureEnabledOptions {\n send_event: boolean\n}\n\nexport interface SessionRecordingOptions {\n blockClass?: string | RegExp\n blockSelector?: string | null\n ignoreClass?: string\n maskTextClass?: string | RegExp\n maskTextSelector?: string | null\n maskTextFn?: ((text: string, element: HTMLElement | null) => string) | null\n maskAllInputs?: boolean\n maskInputOptions?: recordOptions['maskInputOptions']\n maskInputFn?: ((text: string, element?: HTMLElement) => string) | null\n slimDOMOptions?: recordOptions['slimDOMOptions']\n collectFonts?: boolean\n inlineStylesheet?: boolean\n recordCrossOriginIframes?: boolean\n /**\n * Allows local config to override remote canvas recording settings from the decide response\n */\n captureCanvas?: SessionRecordingCanvasOptions\n /** @deprecated - use maskCapturedNetworkRequestFn instead */\n maskNetworkRequestFn?: ((data: NetworkRequest) => NetworkRequest | null | undefined) | null\n /** Modify the network request before it is captured. Returning null or undefined stops it being captured */\n maskCapturedNetworkRequestFn?: ((data: CapturedNetworkRequest) => CapturedNetworkRequest | null | undefined) | null\n // our settings here only support a subset of those proposed for rrweb's network capture plugin\n recordHeaders?: boolean\n recordBody?: boolean\n // ADVANCED: while a user is active we take a full snapshot of the browser every interval. For very few sites playback performance might be better with different interval. Set to 0 to disable\n full_snapshot_interval_millis?: number\n /*\n ADVANCED: whether to partially compress rrweb events before sending them to the server,\n defaults to true, can be set to false to disable partial compression\n NB requests are still compressed when sent to the server regardless of this setting\n */\n compress_events?: boolean\n /*\n ADVANCED: alters the threshold before a recording considers a user has become idle.\n Normally only altered alongside changes to session_idle_timeout_ms.\n Default is 5 minutes.\n */\n session_idle_threshold_ms?: number\n /*\n ADVANCED: alters the refill rate for the token bucket mutation throttling\n Normally only altered alongside posthog support guidance.\n Accepts values between 0 and 100\n Default is 10.\n */\n __mutationRateLimiterRefillRate?: number\n /*\n ADVANCED: alters the bucket size for the token bucket mutation throttling\n Normally only altered alongside posthog support guidance.\n Accepts values between 0 and 100\n Default is 100.\n */\n __mutationRateLimiterBucketSize?: number\n}\n\nexport type SessionIdChangedCallback = (\n sessionId: string,\n windowId: string | null | undefined,\n changeReason?: { noSessionId: boolean; activityTimeout: boolean; sessionPastMaximumLength: boolean }\n) => void\n\nexport enum Compression {\n GZipJS = 'gzip-js',\n Base64 = 'base64',\n}\n\n// Request types - these should be kept minimal to what request.ts needs\n\n// Minimal class to allow interop between different request methods (xhr / fetch)\nexport interface RequestResponse {\n statusCode: number\n text?: string\n json?: any\n}\n\nexport type RequestCallback = (response: RequestResponse) => void\n\n// See https://nextjs.org/docs/app/api-reference/functions/fetch#fetchurl-options\ntype NextOptions = { revalidate: false | 0 | number; tags: string[] }\n\nexport interface RequestOptions {\n url: string\n // Data can be a single object or an array of objects when batched\n data?: Record<string, any> | Record<string, any>[]\n headers?: Record<string, any>\n transport?: 'XHR' | 'fetch' | 'sendBeacon'\n method?: 'POST' | 'GET'\n urlQueryArgs?: { compression: Compression }\n callback?: RequestCallback\n timeout?: number\n noRetries?: boolean\n compression?: Compression | 'best-available'\n fetchOptions?: {\n cache?: RequestInit['cache']\n next?: NextOptions\n }\n}\n\n// Queued request types - the same as a request but with additional queueing information\n\nexport interface QueuedRequestOptions extends RequestOptions {\n batchKey?: string /** key of queue, e.g. 'sessionRecording' vs 'event' */\n}\n\n// Used explicitly for retriable requests\nexport interface RetriableRequestOptions extends QueuedRequestOptions {\n retriesPerformedSoFar?: number\n}\n\nexport interface CaptureOptions {\n $set?: Properties /** used with $identify */\n $set_once?: Properties /** used with $identify */\n _url?: string /** Used to override the desired endpoint for the captured event */\n _batchKey?: string /** key of queue, e.g. 'sessionRecording' vs 'event' */\n _noTruncate?: boolean /** if set, overrides and disables config.properties_string_max_length */\n send_instantly?: boolean /** if set skips the batched queue */\n skip_client_rate_limiting?: boolean /** if set skips the client side rate limiting */\n transport?: RequestOptions['transport'] /** if set, overrides the desired transport method */\n timestamp?: Date\n}\n\nexport type FlagVariant = { flag: string; variant: string }\n\nexport type SessionRecordingCanvasOptions = {\n recordCanvas?: boolean | null\n canvasFps?: number | null\n // the API returns a decimal between 0 and 1 as a string\n canvasQuality?: string | null\n}\n\nexport interface RemoteConfig {\n supportedCompression: Compression[]\n autocapture_opt_out?: boolean\n /**\n * originally capturePerformance was replay only and so boolean true\n * is equivalent to { network_timing: true }\n * now capture performance can be separately enabled within replay\n * and as a standalone web vitals tracker\n * people can have them enabled separately\n * they work standalone but enhance each other\n * TODO: deprecate this so we make a new config that doesn't need this explanation\n */\n capturePerformance?: boolean | PerformanceCaptureConfig\n analytics?: {\n endpoint?: string\n }\n elementsChainAsString?: boolean\n // this is currently in development and may have breaking changes without a major version bump\n autocaptureExceptions?:\n | boolean\n | {\n endpoint?: string\n }\n sessionRecording?: SessionRecordingCanvasOptions & {\n endpoint?: string\n consoleLogRecordingEnabled?: boolean\n // the API returns a decimal between 0 and 1 as a string\n sampleRate?: string | null\n minimumDurationMilliseconds?: number\n linkedFlag?: string | FlagVariant | null\n networkPayloadCapture?: Pick<NetworkRecordOptions, 'recordBody' | 'recordHeaders'>\n urlTriggers?: SessionRecordingUrlTrigger[]\n scriptConfig?: { script?: string | undefined }\n urlBlocklist?: SessionRecordingUrlTrigger[]\n eventTriggers?: string[]\n }\n surveys?: boolean\n toolbarParams: ToolbarParams\n editorParams?: ToolbarParams /** @deprecated, renamed to toolbarParams, still present on older API responses */\n toolbarVersion: 'toolbar' /** @deprecated, moved to toolbarParams */\n isAuthenticated: boolean\n siteApps: { id: string; url: string }[]\n heatmaps?: boolean\n defaultIdentifiedOnly?: boolean\n captureDeadClicks?: boolean\n hasFeatureFlags?: boolean // Indicates if the team has any flags enabled (if not we don't need to load them)\n}\n\nexport interface DecideResponse extends RemoteConfig {\n featureFlags: Record<string, string | boolean>\n featureFlagPayloads: Record<string, JsonType>\n errorsWhileComputingFlags: boolean\n}\n\nexport type SiteAppGlobals = {\n event: {\n uuid: string\n event: EventName\n properties: Properties\n timestamp?: Date\n elements_chain?: string\n distinct_id?: string\n }\n person: {\n properties: Properties\n }\n groups: Record<string, { id: string; type: string; properties: Properties }>\n}\n\nexport type SiteAppLoader = {\n id: string\n init: (config: { posthog: PostHog; callback: (success: boolean) => void }) => {\n processEvent?: (globals: SiteAppGlobals) => void\n }\n}\n\nexport type SiteApp = {\n id: string\n loaded: boolean\n errored: boolean\n processEvent?: (globals: SiteAppGlobals) => void\n}\n\nexport type FeatureFlagsCallback = (\n flags: string[],\n variants: Record<string, string | boolean>,\n context?: {\n errorsLoading?: boolean\n }\n) => void\n\nexport interface PersistentStore {\n is_supported: () => boolean\n error: (error: any) => void\n parse: (name: string) => any\n get: (name: string) => any\n set: (\n name: string,\n value: any,\n expire_days?: number | null,\n cross_subdomain?: boolean,\n secure?: boolean,\n debug?: boolean\n ) => void\n remove: (name: string, cross_subdomain?: boolean) => void\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport type Breaker = {}\nexport type EventHandler = (event: Event) => boolean | void\n\nexport type ToolbarUserIntent = 'add-action' | 'edit-action'\nexport type ToolbarSource = 'url' | 'localstorage'\nexport type ToolbarVersion = 'toolbar'\n\n/* sync with posthog */\nexport interface ToolbarParams {\n token?: string /** public posthog-js token */\n temporaryToken?: string /** private temporary user token */\n actionId?: number\n userIntent?: ToolbarUserIntent\n source?: ToolbarSource\n toolbarVersion?: ToolbarVersion\n instrument?: boolean\n distinctId?: string\n userEmail?: string\n dataAttributes?: string[]\n featureFlags?: Record<string, string | boolean>\n}\n\nexport type SnippetArrayItem = [method: string, ...args: any[]]\n\nexport type JsonRecord = { [key: string]: JsonType }\nexport type JsonType = string | number | boolean | null | JsonRecord | Array<JsonType>\n\n/** A feature that isn't publicly available yet.*/\nexport interface EarlyAccessFeature {\n // Sync this with the backend's EarlyAccessFeatureSerializer!\n name: string\n description: string\n stage: 'concept' | 'alpha' | 'beta'\n documentationUrl: string | null\n flagKey: string | null\n}\n\nexport type EarlyAccessFeatureCallback = (earlyAccessFeatures: EarlyAccessFeature[]) => void\n\nexport interface EarlyAccessFeatureResponse {\n earlyAccessFeatures: EarlyAccessFeature[]\n}\n\nexport type Headers = Record<string, string>\n\n/* for rrweb/network@1\n ** when that is released as part of rrweb this can be removed\n ** don't rely on this type, it may change without notice\n */\nexport type InitiatorType =\n | 'audio'\n | 'beacon'\n | 'body'\n | 'css'\n | 'early-hint'\n | 'embed'\n | 'fetch'\n | 'frame'\n | 'iframe'\n | 'icon'\n | 'image'\n | 'img'\n | 'input'\n | 'link'\n | 'navigation'\n | 'object'\n | 'ping'\n | 'script'\n | 'track'\n | 'video'\n | 'xmlhttprequest'\n\nexport type NetworkRecordOptions = {\n initiatorTypes?: InitiatorType[]\n maskRequestFn?: (data: CapturedNetworkRequest) => CapturedNetworkRequest | undefined\n recordHeaders?: boolean | { request: boolean; response: boolean }\n recordBody?: boolean | string[] | { request: boolean | string[]; response: boolean | string[] }\n recordInitialRequests?: boolean\n /**\n * whether to record PerformanceEntry events for network requests\n */\n recordPerformance?: boolean\n /**\n * the PerformanceObserver will only observe these entry types\n */\n performanceEntryTypeToObserve: string[]\n /**\n * the maximum size of the request/response body to record\n * NB this will be at most 1MB even if set larger\n */\n payloadSizeLimitBytes: number\n /**\n * some domains we should never record the payload\n * for example other companies session replay ingestion payloads aren't super useful but are gigantic\n * if this isn't provided we use a default list\n * if this is provided - we add the provided list to the default list\n * i.e. we never record the payloads on the default deny list\n */\n payloadHostDenyList?: string[]\n}\n\n/** @deprecated - use CapturedNetworkRequest instead */\nexport type NetworkRequest = {\n url: string\n}\n\n// In rrweb this is called NetworkRequest, but we already exposed that as having only URL\n// we also want to vary from the rrweb NetworkRequest because we want to include\n// all PerformanceEntry properties too.\n// that has 4 required properties\n// readonly duration: DOMHighResTimeStamp;\n// readonly entryType: string;\n// readonly name: string;\n// readonly startTime: DOMHighResTimeStamp;\n// NB: properties below here are ALPHA, don't rely on them, they may change without notice\n\n// we mirror PerformanceEntry since we read into this type from a PerformanceObserver,\n// but we don't want to inherit its readonly-iness\ntype Writable<T> = { -readonly [P in keyof T]: T[P] }\n\nexport type CapturedNetworkRequest = Writable<Omit<PerformanceEntry, 'toJSON'>> & {\n // properties below here are ALPHA, don't rely on them, they may change without notice\n method?: string\n initiatorType?: InitiatorType\n status?: number\n timeOrigin?: number\n timestamp?: number\n startTime?: number\n endTime?: number\n requestHeaders?: Headers\n requestBody?: string | null\n responseHeaders?: Headers\n responseBody?: string | null\n // was this captured before fetch/xhr could have been wrapped\n isInitial?: boolean\n}\n\nexport type ErrorEventArgs = [\n event: string | Event,\n source?: string | undefined,\n lineno?: number | undefined,\n colno?: number | undefined,\n error?: Error | undefined\n]\n\nexport type ErrorMetadata = {\n handled?: boolean\n synthetic?: boolean\n syntheticException?: Error\n overrideExceptionType?: string\n overrideExceptionMessage?: string\n defaultExceptionType?: string\n defaultExceptionMessage?: string\n}\n\n// levels originally copied from Sentry to work with the sentry integration\n// and to avoid relying on a frequently changing @sentry/types dependency\n// but provided as an array of literal types, so we can constrain the level below\nexport const severityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'] as const\nexport declare type SeverityLevel = typeof severityLevels[number]\n\nexport interface ErrorProperties {\n $exception_type: string\n $exception_message: string\n $exception_level: SeverityLevel\n $exception_source?: string\n $exception_lineno?: number\n $exception_colno?: number\n $exception_DOMException_code?: string\n $exception_is_synthetic?: boolean\n $exception_stack_trace_raw?: string\n $exception_handled?: boolean\n $exception_personURL?: string\n}\n\nexport interface ErrorConversions {\n errorToProperties: (args: ErrorEventArgs) => ErrorProperties\n unhandledRejectionToProperties: (args: [ev: PromiseRejectionEvent]) => ErrorProperties\n}\n\nexport interface SessionRecordingUrlTrigger {\n url: string\n matching: 'regex'\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAOA,MAAM,CAAC,IAAM,sBAAsB,GAAG,mBAAmB,CAAA;AAEzD,MAAM,CAAC,IAAM,wBAAwB,GAAG;IACpC,WAAW;IACX,WAAW;IACX,YAAY;IACZ,MAAM;IACN,kBAAkB;IAClB,aAAa;IACb,cAAc;IACd,WAAW;IACX,gBAAgB;IAChB,eAAe;IACf,4BAA4B;IAC5B,yBAAyB;IACzB,4BAA4B;IAC5B,sBAAsB;CAChB,CAAA;AAiaV,MAAM,CAAN,IAAY,WAGX;AAHD,WAAY,WAAW;IACnB,iCAAkB,CAAA;IAClB,gCAAiB,CAAA;AACrB,CAAC,EAHW,WAAW,KAAX,WAAW,QAGtB;AAyUD,2EAA2E;AAC3E,yEAAyE;AACzE,iFAAiF;AACjF,MAAM,CAAC,IAAM,cAAc,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAU,CAAA","sourcesContent":["import { PostHog } from './posthog-core'\nimport type { SegmentAnalytics } from './extensions/segment-integration'\nimport { recordOptions } from './extensions/replay/sessionrecording-utils'\n\nexport type Property = any\nexport type Properties = Record<string, Property>\n\nexport const COPY_AUTOCAPTURE_EVENT = '$copy_autocapture'\n\nexport const knownUnsafeEditableEvent = [\n '$snapshot',\n '$pageview',\n '$pageleave',\n '$set',\n 'survey dismissed',\n 'survey sent',\n 'survey shown',\n '$identify',\n '$groupidentify',\n '$create_alias',\n '$$client_ingestion_warning',\n '$web_experiment_applied',\n '$feature_enrollment_update',\n '$feature_flag_called',\n] as const\n\n/**\n * These events can be processed by the `beforeCapture` function\n * but can cause unexpected confusion in data.\n *\n * Some features of PostHog rely on receiving 100% of these events\n */\nexport type KnownUnsafeEditableEvent = typeof knownUnsafeEditableEvent[number]\n\n/**\n * These are known events PostHog events that can be processed by the `beforeCapture` function\n * That means PostHog functionality does not rely on receiving 100% of these for calculations\n * So, it is safe to sample them to reduce the volume of events sent to PostHog\n */\nexport type KnownEventName =\n | '$heatmaps_data'\n | '$opt_in'\n | '$exception'\n | '$$heatmap'\n | '$web_vitals'\n | '$dead_click'\n | '$autocapture'\n | typeof COPY_AUTOCAPTURE_EVENT\n | '$rageclick'\n\nexport type EventName =\n | KnownUnsafeEditableEvent\n | KnownEventName\n // magic value so that the type of EventName is a set of known strings or any other string\n // which means you get autocomplete for known strings\n // but no type complaints when you add an arbitrary string\n | (string & {})\n\nexport interface CaptureResult {\n uuid: string\n event: EventName\n properties: Properties\n $set?: Properties\n $set_once?: Properties\n timestamp?: Date\n}\n\nexport type AutocaptureCompatibleElement = 'a' | 'button' | 'form' | 'input' | 'select' | 'textarea' | 'label'\nexport type DomAutocaptureEvents = 'click' | 'change' | 'submit'\n\n/**\n * If an array is passed for an allowlist, autocapture events will only be sent for elements matching\n * at least one of the elements in the array. Multiple allowlists can be used\n */\nexport interface AutocaptureConfig {\n /**\n * List of URLs to allow autocapture on, can be strings to match\n * or regexes e.g. ['https://example.com', 'test.com/.*']\n * this is useful when you want to autocapture on specific pages only\n *\n * if you set both url_allowlist and url_ignorelist,\n * we check the allowlist first and then the ignorelist.\n * the ignorelist can override the allowlist\n */\n url_allowlist?: (string | RegExp)[]\n\n /**\n * List of URLs to not allow autocapture on, can be strings to match\n * or regexes e.g. ['https://example.com', 'test.com/.*']\n * this is useful when you want to autocapture on most pages but not some specific ones\n *\n * if you set both url_allowlist and url_ignorelist,\n * we check the allowlist first and then the ignorelist.\n * the ignorelist can override the allowlist\n */\n url_ignorelist?: (string | RegExp)[]\n\n /**\n * List of DOM events to allow autocapture on e.g. ['click', 'change', 'submit']\n */\n dom_event_allowlist?: DomAutocaptureEvents[]\n\n /**\n * List of DOM elements to allow autocapture on\n * e.g. ['a', 'button', 'form', 'input', 'select', 'textarea', 'label']\n * we consider the tree of elements from the root to the target element of the click event\n * so for the tree div > div > button > svg\n * if the allowlist has button then we allow the capture when the button or the svg is the click target\n * but not if either of the divs are detected as the click target\n */\n element_allowlist?: AutocaptureCompatibleElement[]\n\n /**\n * List of CSS selectors to allow autocapture on\n * e.g. ['[ph-capture]']\n * we consider the tree of elements from the root to the target element of the click event\n * so for the tree div > div > button > svg\n * and allow list config `['[id]']`\n * we will capture the click if the click-target or its parents has any id\n */\n css_selector_allowlist?: string[]\n\n /**\n * Exclude certain element attributes from autocapture\n * E.g. ['aria-label'] or [data-attr-pii]\n */\n element_attribute_ignorelist?: string[]\n\n capture_copied_text?: boolean\n}\n\nexport interface BootstrapConfig {\n distinctID?: string\n isIdentifiedID?: boolean\n featureFlags?: Record<string, boolean | string>\n featureFlagPayloads?: Record<string, JsonType>\n /**\n * Optionally provide a sessionID, this is so that you can provide an existing sessionID here to continue a user's session across a domain or device. It MUST be:\n * - unique to this user\n * - a valid UUID v7\n * - the timestamp part must be <= the timestamp of the first event in the session\n * - the timestamp of the last event in the session must be < the timestamp part + 24 hours\n * **/\n sessionID?: string\n}\n\nexport type SupportedWebVitalsMetrics = 'LCP' | 'CLS' | 'FCP' | 'INP'\n\nexport interface PerformanceCaptureConfig {\n /** works with session replay to use the browser's native performance observer to capture performance metrics */\n network_timing?: boolean\n /** use chrome's web vitals library to wrap fetch and capture web vitals */\n web_vitals?: boolean\n /**\n * We observe very large values reported by the Chrome web vitals library\n * These outliers are likely not real, useful values, and we exclude them\n * You can set this to 0 in order to include all values, NB this is not recommended\n * if not set this defaults to 15 minutes\n */\n __web_vitals_max_value?: number\n /**\n * By default all 4 metrics are captured\n * You can set this config to restrict which metrics are captured\n * e.g. ['CLS', 'FCP'] to only capture those two metrics\n * NB setting this does not override whether the capture is enabled\n */\n web_vitals_allowed_metrics?: SupportedWebVitalsMetrics[]\n /**\n * we delay flushing web vitals metrics to reduce the number of events we send\n * this is the maximum time we will wait before sending the metrics\n * if not set it defaults to 5 seconds\n */\n web_vitals_delayed_flush_ms?: number\n}\n\nexport interface DeadClickCandidate {\n node: Element\n originalEvent: MouseEvent\n timestamp: number\n // time between click and the most recent scroll\n scrollDelayMs?: number\n // time between click and the most recent mutation\n mutationDelayMs?: number\n // time between click and the most recent selection changed event\n selectionChangedDelayMs?: number\n // if neither scroll nor mutation seen before threshold passed\n absoluteDelayMs?: number\n}\n\nexport type DeadClicksAutoCaptureConfig = {\n // by default if a click is followed by a sroll within 100ms it is not a dead click\n scroll_threshold_ms?: number\n // by default if a click is followed by a selection change within 100ms it is not a dead click\n selection_change_threshold_ms?: number\n // by default if a click is followed by a mutation within 2500ms it is not a dead click\n mutation_threshold_ms?: number\n /**\n * Allows setting behavior for when a dead click is captured.\n * For e.g. to support capture to heatmaps\n *\n * If not provided the default behavior is to auto-capture dead click events\n *\n * Only intended to be provided by the SDK\n */\n __onCapture?: ((click: DeadClickCandidate, properties: Properties) => void) | undefined\n} & Pick<AutocaptureConfig, 'element_attribute_ignorelist'>\n\nexport interface HeatmapConfig {\n /*\n * how often to send batched data in $$heatmap_data events\n * if set to 0 or not set, sends using the default interval of 1 second\n * */\n flush_interval_milliseconds: number\n}\n\nexport type BeforeSendFn = (cr: CaptureResult | null) => CaptureResult | null\n\nexport interface PostHogConfig {\n api_host: string\n /** @deprecated - This property is no longer supported */\n api_method?: string\n api_transport?: 'XHR' | 'fetch'\n ui_host: string | null\n token: string\n autocapture: boolean | AutocaptureConfig\n rageclick: boolean\n cross_subdomain_cookie: boolean\n persistence: 'localStorage' | 'cookie' | 'memory' | 'localStorage+cookie' | 'sessionStorage'\n persistence_name: string\n /** @deprecated - Use 'persistence_name' instead */\n cookie_name?: string\n loaded: (posthog_instance: PostHog) => void\n store_google: boolean\n custom_campaign_params: string[]\n // a list of strings to be tested against navigator.userAgent to determine if the source is a bot\n // this is **added to** the default list of bots that we check\n // defaults to the empty array\n custom_blocked_useragents: string[]\n save_referrer: boolean\n verbose: boolean\n capture_pageview: boolean\n capture_pageleave: boolean | 'if_capture_pageview'\n debug: boolean\n cookie_expiration: number\n upgrade: boolean\n disable_session_recording: boolean\n disable_persistence: boolean\n /** @deprecated - use `disable_persistence` instead */\n disable_cookie?: boolean\n disable_surveys: boolean\n disable_web_experiments: boolean\n /** If set, posthog-js will never load external scripts such as those needed for Session Replay or Surveys. */\n disable_external_dependency_loading?: boolean\n enable_recording_console_log?: boolean\n secure_cookie: boolean\n ip: boolean\n /** Starts the SDK in an opted out state requiring opt_in_capturing() to be called before events will b captured */\n opt_out_capturing_by_default: boolean\n opt_out_capturing_persistence_type: 'localStorage' | 'cookie'\n /** If set to true this will disable persistence if the user is opted out of capturing. @default false */\n opt_out_persistence_by_default?: boolean\n /** Opt out of user agent filtering such as googlebot or other bots. Defaults to `false` */\n opt_out_useragent_filter: boolean\n\n opt_out_capturing_cookie_prefix: string | null\n opt_in_site_apps: boolean\n respect_dnt: boolean\n /** @deprecated - use `property_denylist` instead */\n property_blacklist?: string[]\n property_denylist: string[]\n request_headers: { [header_name: string]: string }\n on_request_error?: (error: RequestResponse) => void\n /** @deprecated - use `request_headers` instead */\n xhr_headers?: { [header_name: string]: string }\n /** @deprecated - use `on_request_error` instead */\n on_xhr_error?: (failedRequest: XMLHttpRequest) => void\n inapp_protocol: string\n inapp_link_new_window: boolean\n request_batching: boolean\n sanitize_properties: ((properties: Properties, event_name: string) => Properties) | null\n properties_string_max_length: number\n session_recording: SessionRecordingOptions\n session_idle_timeout_seconds: number\n mask_all_element_attributes: boolean\n mask_all_text: boolean\n advanced_disable_decide: boolean\n advanced_disable_feature_flags: boolean\n advanced_disable_feature_flags_on_first_load: boolean\n advanced_disable_toolbar_metrics: boolean\n feature_flag_request_timeout_ms: number\n get_device_id: (uuid: string) => string\n name: string\n /**\n * this is a read-only function that can be used to react to event capture\n * @deprecated - use `before_send` instead - NB before_send is not read only\n */\n _onCapture: (eventName: string, eventData: CaptureResult) => void\n /**\n * This function or array of functions - if provided - are called immediately before sending data to the server.\n * It allows you to edit data before it is sent, or choose not to send it all.\n * if provided as an array the functions are called in the order they are provided\n * any one function returning null means the event will not be sent\n */\n before_send?: BeforeSendFn | BeforeSendFn[]\n capture_performance?: boolean | PerformanceCaptureConfig\n // Should only be used for testing. Could negatively impact performance.\n disable_compression: boolean\n bootstrap: BootstrapConfig\n segment?: SegmentAnalytics\n __preview_send_client_session_params?: boolean\n /* @deprecated - use `capture_heatmaps` instead */\n enable_heatmaps?: boolean\n capture_heatmaps?: boolean | HeatmapConfig\n capture_dead_clicks?: boolean | DeadClicksAutoCaptureConfig\n disable_scroll_properties?: boolean\n // Let the pageview scroll stats use a custom css selector for the root element, e.g. `main`\n scroll_root_selector?: string | string[]\n\n /** You can control whether events from PostHog-js have person processing enabled with the `person_profiles` config setting. There are three options:\n * - `person_profiles: 'always'` _(default)_ - we will process persons data for all events\n * - `person_profiles: 'never'` - we won't process persons for any event. This means that anonymous users will not be merged once they sign up or login, so you lose the ability to create funnels that track users from anonymous to identified. All events (including `$identify`) will be sent with `$process_person_profile: False`.\n * - `person_profiles: 'identified_only'` - we will only process persons when you call `posthog.identify`, `posthog.alias`, `posthog.setPersonProperties`, `posthog.group`, `posthog.setPersonPropertiesForFlags` or `posthog.setGroupPropertiesForFlags` Anonymous users won't get person profiles.\n */\n person_profiles?: 'always' | 'never' | 'identified_only'\n /** @deprecated - use `person_profiles` instead */\n process_person?: 'always' | 'never' | 'identified_only'\n\n /** Client side rate limiting */\n rate_limiting?: {\n /** The average number of events per second that should be permitted (defaults to 10) */\n events_per_second?: number\n /** How many events can be captured in a burst. This defaults to 10 times the events_per_second count */\n events_burst_limit?: number\n }\n\n /** Used when sending data via `fetch`, use with care, this is intentionally meant to be used with NextJS `fetch`\n * Incorrect usage may cause out-of-date data for feature flags, actions tracking, etc.\n * See https://nextjs.org/docs/app/api-reference/functions/fetch#fetchurl-options\n */\n fetch_options?: {\n cache?: RequestInit['cache']\n next_options?: NextOptions\n }\n\n /**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * whether to wrap fetch and add tracing headers to the request\n * */\n __add_tracing_headers?: boolean\n\n /**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * enables the new RemoteConfig approach to loading config instead of decide\n * */\n __preview_remote_config?: boolean\n\n /**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * whether to send a sentinel value for distinct id, device id, and session id, which will be replaced server-side by a cookieless hash\n * */\n __preview_experimental_cookieless_mode?: boolean\n}\n\nexport interface OptInOutCapturingOptions {\n capture: (event: string, properties: Properties, options: CaptureOptions) => void\n capture_event_name: string\n capture_properties: Properties\n enable_persistence: boolean\n clear_persistence: boolean\n persistence_type: 'cookie' | 'localStorage' | 'localStorage+cookie'\n cookie_prefix: string\n cookie_expiration: number\n cross_subdomain_cookie: boolean\n secure_cookie: boolean\n}\n\nexport interface IsFeatureEnabledOptions {\n send_event: boolean\n}\n\nexport interface SessionRecordingOptions {\n blockClass?: string | RegExp\n blockSelector?: string | null\n ignoreClass?: string\n maskTextClass?: string | RegExp\n maskTextSelector?: string | null\n maskTextFn?: ((text: string, element: HTMLElement | null) => string) | null\n maskAllInputs?: boolean\n maskInputOptions?: recordOptions['maskInputOptions']\n maskInputFn?: ((text: string, element?: HTMLElement) => string) | null\n slimDOMOptions?: recordOptions['slimDOMOptions']\n collectFonts?: boolean\n inlineStylesheet?: boolean\n recordCrossOriginIframes?: boolean\n /**\n * Allows local config to override remote canvas recording settings from the decide response\n */\n captureCanvas?: SessionRecordingCanvasOptions\n /** @deprecated - use maskCapturedNetworkRequestFn instead */\n maskNetworkRequestFn?: ((data: NetworkRequest) => NetworkRequest | null | undefined) | null\n /** Modify the network request before it is captured. Returning null or undefined stops it being captured */\n maskCapturedNetworkRequestFn?: ((data: CapturedNetworkRequest) => CapturedNetworkRequest | null | undefined) | null\n // our settings here only support a subset of those proposed for rrweb's network capture plugin\n recordHeaders?: boolean\n recordBody?: boolean\n // ADVANCED: while a user is active we take a full snapshot of the browser every interval. For very few sites playback performance might be better with different interval. Set to 0 to disable\n full_snapshot_interval_millis?: number\n /*\n ADVANCED: whether to partially compress rrweb events before sending them to the server,\n defaults to true, can be set to false to disable partial compression\n NB requests are still compressed when sent to the server regardless of this setting\n */\n compress_events?: boolean\n /*\n ADVANCED: alters the threshold before a recording considers a user has become idle.\n Normally only altered alongside changes to session_idle_timeout_ms.\n Default is 5 minutes.\n */\n session_idle_threshold_ms?: number\n /*\n ADVANCED: alters the refill rate for the token bucket mutation throttling\n Normally only altered alongside posthog support guidance.\n Accepts values between 0 and 100\n Default is 10.\n */\n __mutationRateLimiterRefillRate?: number\n /*\n ADVANCED: alters the bucket size for the token bucket mutation throttling\n Normally only altered alongside posthog support guidance.\n Accepts values between 0 and 100\n Default is 100.\n */\n __mutationRateLimiterBucketSize?: number\n}\n\nexport type SessionIdChangedCallback = (\n sessionId: string,\n windowId: string | null | undefined,\n changeReason?: { noSessionId: boolean; activityTimeout: boolean; sessionPastMaximumLength: boolean }\n) => void\n\nexport enum Compression {\n GZipJS = 'gzip-js',\n Base64 = 'base64',\n}\n\n// Request types - these should be kept minimal to what request.ts needs\n\n// Minimal class to allow interop between different request methods (xhr / fetch)\nexport interface RequestResponse {\n statusCode: number\n text?: string\n json?: any\n}\n\nexport type RequestCallback = (response: RequestResponse) => void\n\n// See https://nextjs.org/docs/app/api-reference/functions/fetch#fetchurl-options\ntype NextOptions = { revalidate: false | 0 | number; tags: string[] }\n\nexport interface RequestOptions {\n url: string\n // Data can be a single object or an array of objects when batched\n data?: Record<string, any> | Record<string, any>[]\n headers?: Record<string, any>\n transport?: 'XHR' | 'fetch' | 'sendBeacon'\n method?: 'POST' | 'GET'\n urlQueryArgs?: { compression: Compression }\n callback?: RequestCallback\n timeout?: number\n noRetries?: boolean\n compression?: Compression | 'best-available'\n fetchOptions?: {\n cache?: RequestInit['cache']\n next?: NextOptions\n }\n}\n\n// Queued request types - the same as a request but with additional queueing information\n\nexport interface QueuedRequestOptions extends RequestOptions {\n batchKey?: string /** key of queue, e.g. 'sessionRecording' vs 'event' */\n}\n\n// Used explicitly for retriable requests\nexport interface RetriableRequestOptions extends QueuedRequestOptions {\n retriesPerformedSoFar?: number\n}\n\nexport interface CaptureOptions {\n $set?: Properties /** used with $identify */\n $set_once?: Properties /** used with $identify */\n _url?: string /** Used to override the desired endpoint for the captured event */\n _batchKey?: string /** key of queue, e.g. 'sessionRecording' vs 'event' */\n _noTruncate?: boolean /** if set, overrides and disables config.properties_string_max_length */\n send_instantly?: boolean /** if set skips the batched queue */\n skip_client_rate_limiting?: boolean /** if set skips the client side rate limiting */\n transport?: RequestOptions['transport'] /** if set, overrides the desired transport method */\n timestamp?: Date\n}\n\nexport type FlagVariant = { flag: string; variant: string }\n\nexport type SessionRecordingCanvasOptions = {\n recordCanvas?: boolean | null\n canvasFps?: number | null\n // the API returns a decimal between 0 and 1 as a string\n canvasQuality?: string | null\n}\n\nexport interface RemoteConfig {\n supportedCompression: Compression[]\n autocapture_opt_out?: boolean\n /**\n * originally capturePerformance was replay only and so boolean true\n * is equivalent to { network_timing: true }\n * now capture performance can be separately enabled within replay\n * and as a standalone web vitals tracker\n * people can have them enabled separately\n * they work standalone but enhance each other\n * TODO: deprecate this so we make a new config that doesn't need this explanation\n */\n capturePerformance?: boolean | PerformanceCaptureConfig\n analytics?: {\n endpoint?: string\n }\n elementsChainAsString?: boolean\n // this is currently in development and may have breaking changes without a major version bump\n autocaptureExceptions?:\n | boolean\n | {\n endpoint?: string\n }\n sessionRecording?: SessionRecordingCanvasOptions & {\n endpoint?: string\n consoleLogRecordingEnabled?: boolean\n // the API returns a decimal between 0 and 1 as a string\n sampleRate?: string | null\n minimumDurationMilliseconds?: number\n linkedFlag?: string | FlagVariant | null\n networkPayloadCapture?: Pick<NetworkRecordOptions, 'recordBody' | 'recordHeaders'>\n urlTriggers?: SessionRecordingUrlTrigger[]\n scriptConfig?: { script?: string | undefined }\n urlBlocklist?: SessionRecordingUrlTrigger[]\n eventTriggers?: string[]\n }\n surveys?: boolean\n toolbarParams: ToolbarParams\n editorParams?: ToolbarParams /** @deprecated, renamed to toolbarParams, still present on older API responses */\n toolbarVersion: 'toolbar' /** @deprecated, moved to toolbarParams */\n isAuthenticated: boolean\n siteApps: { id: string; url: string }[]\n heatmaps?: boolean\n defaultIdentifiedOnly?: boolean\n captureDeadClicks?: boolean\n hasFeatureFlags?: boolean // Indicates if the team has any flags enabled (if not we don't need to load them)\n}\n\nexport interface DecideResponse extends RemoteConfig {\n featureFlags: Record<string, string | boolean>\n featureFlagPayloads: Record<string, JsonType>\n errorsWhileComputingFlags: boolean\n}\n\nexport type SiteAppGlobals = {\n event: {\n uuid: string\n event: EventName\n properties: Properties\n timestamp?: Date\n elements_chain?: string\n distinct_id?: string\n }\n person: {\n properties: Properties\n }\n groups: Record<string, { id: string; type: string; properties: Properties }>\n}\n\nexport type SiteAppLoader = {\n id: string\n init: (config: { posthog: PostHog; callback: (success: boolean) => void }) => {\n processEvent?: (globals: SiteAppGlobals) => void\n }\n}\n\nexport type SiteApp = {\n id: string\n loaded: boolean\n errored: boolean\n processEvent?: (globals: SiteAppGlobals) => void\n}\n\nexport type FeatureFlagsCallback = (\n flags: string[],\n variants: Record<string, string | boolean>,\n context?: {\n errorsLoading?: boolean\n }\n) => void\n\nexport interface PersistentStore {\n is_supported: () => boolean\n error: (error: any) => void\n parse: (name: string) => any\n get: (name: string) => any\n set: (\n name: string,\n value: any,\n expire_days?: number | null,\n cross_subdomain?: boolean,\n secure?: boolean,\n debug?: boolean\n ) => void\n remove: (name: string, cross_subdomain?: boolean) => void\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport type Breaker = {}\nexport type EventHandler = (event: Event) => boolean | void\n\nexport type ToolbarUserIntent = 'add-action' | 'edit-action'\nexport type ToolbarSource = 'url' | 'localstorage'\nexport type ToolbarVersion = 'toolbar'\n\n/* sync with posthog */\nexport interface ToolbarParams {\n token?: string /** public posthog-js token */\n temporaryToken?: string /** private temporary user token */\n actionId?: number\n userIntent?: ToolbarUserIntent\n source?: ToolbarSource\n toolbarVersion?: ToolbarVersion\n instrument?: boolean\n distinctId?: string\n userEmail?: string\n dataAttributes?: string[]\n featureFlags?: Record<string, string | boolean>\n}\n\nexport type SnippetArrayItem = [method: string, ...args: any[]]\n\nexport type JsonRecord = { [key: string]: JsonType }\nexport type JsonType = string | number | boolean | null | JsonRecord | Array<JsonType>\n\n/** A feature that isn't publicly available yet.*/\nexport interface EarlyAccessFeature {\n // Sync this with the backend's EarlyAccessFeatureSerializer!\n name: string\n description: string\n stage: 'concept' | 'alpha' | 'beta'\n documentationUrl: string | null\n flagKey: string | null\n}\n\nexport type EarlyAccessFeatureCallback = (earlyAccessFeatures: EarlyAccessFeature[]) => void\n\nexport interface EarlyAccessFeatureResponse {\n earlyAccessFeatures: EarlyAccessFeature[]\n}\n\nexport type Headers = Record<string, string>\n\n/* for rrweb/network@1\n ** when that is released as part of rrweb this can be removed\n ** don't rely on this type, it may change without notice\n */\nexport type InitiatorType =\n | 'audio'\n | 'beacon'\n | 'body'\n | 'css'\n | 'early-hint'\n | 'embed'\n | 'fetch'\n | 'frame'\n | 'iframe'\n | 'icon'\n | 'image'\n | 'img'\n | 'input'\n | 'link'\n | 'navigation'\n | 'object'\n | 'ping'\n | 'script'\n | 'track'\n | 'video'\n | 'xmlhttprequest'\n\nexport type NetworkRecordOptions = {\n initiatorTypes?: InitiatorType[]\n maskRequestFn?: (data: CapturedNetworkRequest) => CapturedNetworkRequest | undefined\n recordHeaders?: boolean | { request: boolean; response: boolean }\n recordBody?: boolean | string[] | { request: boolean | string[]; response: boolean | string[] }\n recordInitialRequests?: boolean\n /**\n * whether to record PerformanceEntry events for network requests\n */\n recordPerformance?: boolean\n /**\n * the PerformanceObserver will only observe these entry types\n */\n performanceEntryTypeToObserve: string[]\n /**\n * the maximum size of the request/response body to record\n * NB this will be at most 1MB even if set larger\n */\n payloadSizeLimitBytes: number\n /**\n * some domains we should never record the payload\n * for example other companies session replay ingestion payloads aren't super useful but are gigantic\n * if this isn't provided we use a default list\n * if this is provided - we add the provided list to the default list\n * i.e. we never record the payloads on the default deny list\n */\n payloadHostDenyList?: string[]\n}\n\n/** @deprecated - use CapturedNetworkRequest instead */\nexport type NetworkRequest = {\n url: string\n}\n\n// In rrweb this is called NetworkRequest, but we already exposed that as having only URL\n// we also want to vary from the rrweb NetworkRequest because we want to include\n// all PerformanceEntry properties too.\n// that has 4 required properties\n// readonly duration: DOMHighResTimeStamp;\n// readonly entryType: string;\n// readonly name: string;\n// readonly startTime: DOMHighResTimeStamp;\n// NB: properties below here are ALPHA, don't rely on them, they may change without notice\n\n// we mirror PerformanceEntry since we read into this type from a PerformanceObserver,\n// but we don't want to inherit its readonly-iness\ntype Writable<T> = { -readonly [P in keyof T]: T[P] }\n\nexport type CapturedNetworkRequest = Writable<Omit<PerformanceEntry, 'toJSON'>> & {\n // properties below here are ALPHA, don't rely on them, they may change without notice\n method?: string\n initiatorType?: InitiatorType\n status?: number\n timeOrigin?: number\n timestamp?: number\n startTime?: number\n endTime?: number\n requestHeaders?: Headers\n requestBody?: string | null\n responseHeaders?: Headers\n responseBody?: string | null\n // was this captured before fetch/xhr could have been wrapped\n isInitial?: boolean\n}\n\nexport type ErrorEventArgs = [\n event: string | Event,\n source?: string | undefined,\n lineno?: number | undefined,\n colno?: number | undefined,\n error?: Error | undefined\n]\n\nexport type ErrorMetadata = {\n handled?: boolean\n synthetic?: boolean\n syntheticException?: Error\n overrideExceptionType?: string\n overrideExceptionMessage?: string\n defaultExceptionType?: string\n defaultExceptionMessage?: string\n}\n\n// levels originally copied from Sentry to work with the sentry integration\n// and to avoid relying on a frequently changing @sentry/types dependency\n// but provided as an array of literal types, so we can constrain the level below\nexport const severityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'] as const\nexport declare type SeverityLevel = typeof severityLevels[number]\n\nexport interface ErrorProperties {\n $exception_type: string\n $exception_message: string\n $exception_level: SeverityLevel\n $exception_source?: string\n $exception_lineno?: number\n $exception_colno?: number\n $exception_DOMException_code?: string\n $exception_is_synthetic?: boolean\n $exception_stack_trace_raw?: string\n $exception_handled?: boolean\n $exception_personURL?: string\n}\n\nexport interface ErrorConversions {\n errorToProperties: (args: ErrorEventArgs) => ErrorProperties\n unhandledRejectionToProperties: (args: [ev: PromiseRejectionEvent]) => ErrorProperties\n}\n\nexport interface SessionRecordingUrlTrigger {\n url: string\n matching: 'regex'\n}\n"]}
@@ -42,8 +42,8 @@ interface PostHogExtensions {
42
42
  onINP: (metric: any) => void;
43
43
  };
44
44
  tracingHeadersPatchFns?: {
45
- _patchFetch: (sessionManager: SessionIdManager) => () => void;
46
- _patchXHR: (sessionManager: any) => () => void;
45
+ _patchFetch: (sessionManager?: SessionIdManager) => () => void;
46
+ _patchXHR: (sessionManager?: SessionIdManager) => () => void;
47
47
  };
48
48
  initDeadClicksAutocapture?: (ph: PostHog, config: DeadClicksAutoCaptureConfig) => LazyLoadedDeadClicksAutocaptureInterface;
49
49
  }
@@ -1 +1 @@
1
- {"version":3,"file":"globals.js","sourceRoot":"","sources":["../../../src/utils/globals.ts"],"names":[],"mappings":"AAYA;;;;;;;;GAQG;AAEH,iDAAiD;AACjD,IAAM,GAAG,GAA6C,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAA;AAmExG,IAAM,MAAM,GAAkC,OAAO,UAAU,KAAK,WAAW,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,GAAG,CAAA;AAElG,MAAM,CAAC,IAAM,UAAU,GAAG,KAAK,CAAC,SAAS,CAAA;AACzC,MAAM,CAAC,IAAM,aAAa,GAAG,UAAU,CAAC,OAAO,CAAA;AAC/C,MAAM,CAAC,IAAM,aAAa,GAAG,UAAU,CAAC,OAAO,CAAA;AAE/C,MAAM,CAAC,IAAM,SAAS,GAAG,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,SAAS,CAAA;AAC1C,MAAM,CAAC,IAAM,QAAQ,GAAG,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,QAAQ,CAAA;AACxC,MAAM,CAAC,IAAM,QAAQ,GAAG,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,QAAQ,CAAA;AACxC,MAAM,CAAC,IAAM,KAAK,GAAG,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,KAAK,CAAA;AAClC,MAAM,CAAC,IAAM,cAAc,GACvB,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,cAAc,KAAI,iBAAiB,IAAI,IAAI,MAAM,CAAC,cAAc,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS,CAAA;AAClH,MAAM,CAAC,IAAM,eAAe,GAAG,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,eAAe,CAAA;AACtD,MAAM,CAAC,IAAM,SAAS,GAAG,SAAS,aAAT,SAAS,uBAAT,SAAS,CAAE,SAAS,CAAA;AAC7C,MAAM,CAAC,IAAM,gBAAgB,GAAqB,GAAG,aAAH,GAAG,cAAH,GAAG,GAAK,EAAU,CAAA;AAEpE,OAAO,EAAE,GAAG,IAAI,MAAM,EAAE,CAAA","sourcesContent":["import { ErrorProperties } from '../extensions/exception-autocapture/error-conversion'\nimport type { PostHog } from '../posthog-core'\nimport { SessionIdManager } from '../sessionid'\nimport {\n DeadClicksAutoCaptureConfig,\n ErrorEventArgs,\n ErrorMetadata,\n Properties,\n RemoteConfig,\n SiteAppLoader,\n} from '../types'\n\n/*\n * Global helpers to protect access to browser globals in a way that is safer for different targets\n * like DOM, SSR, Web workers etc.\n *\n * NOTE: Typically we want the \"window\" but globalThis works for both the typical browser context as\n * well as other contexts such as the web worker context. Window is still exported for any bits that explicitly require it.\n * If in doubt - export the global you need from this file and use that as an optional value. This way the code path is forced\n * to handle the case where the global is not available.\n */\n\n// eslint-disable-next-line no-restricted-globals\nconst win: (Window & typeof globalThis) | undefined = typeof window !== 'undefined' ? window : undefined\n\nexport type AssignableWindow = Window &\n typeof globalThis &\n Record<string, any> & {\n __PosthogExtensions__?: PostHogExtensions\n _POSTHOG_CONFIG?: RemoteConfig\n _POSTHOG_JS_APPS?: SiteAppLoader[]\n }\n\n/**\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n * changes to this interface can be breaking changes for users of the SDK\n */\n\nexport type PostHogExtensionKind =\n | 'toolbar'\n | 'exception-autocapture'\n | 'web-vitals'\n | 'recorder'\n | 'tracing-headers'\n | 'surveys'\n | 'dead-clicks-autocapture'\n | 'remote-config'\n\nexport interface LazyLoadedDeadClicksAutocaptureInterface {\n start: (observerTarget: Node) => void\n stop: () => void\n}\n\ninterface PostHogExtensions {\n loadExternalDependency?: (\n posthog: PostHog,\n kind: PostHogExtensionKind,\n callback: (error?: string | Event, event?: Event) => void\n ) => void\n\n loadSiteApp?: (posthog: PostHog, appUrl: string, callback: (error?: string | Event, event?: Event) => void) => void\n\n parseErrorAsProperties?: (\n [event, source, lineno, colno, error]: ErrorEventArgs,\n metadata?: ErrorMetadata\n ) => ErrorProperties\n errorWrappingFunctions?: {\n wrapOnError: (captureFn: (props: Properties) => void) => () => void\n wrapUnhandledRejection: (captureFn: (props: Properties) => void) => () => void\n }\n rrweb?: { record: any; version: string }\n rrwebPlugins?: { getRecordConsolePlugin: any; getRecordNetworkPlugin?: any }\n canActivateRepeatedly?: (survey: any) => boolean\n generateSurveys?: (posthog: PostHog) => any | undefined\n postHogWebVitalsCallbacks?: {\n onLCP: (metric: any) => void\n onCLS: (metric: any) => void\n onFCP: (metric: any) => void\n onINP: (metric: any) => void\n }\n tracingHeadersPatchFns?: {\n _patchFetch: (sessionManager: SessionIdManager) => () => void\n _patchXHR: (sessionManager: any) => () => void\n }\n initDeadClicksAutocapture?: (\n ph: PostHog,\n config: DeadClicksAutoCaptureConfig\n ) => LazyLoadedDeadClicksAutocaptureInterface\n}\n\nconst global: typeof globalThis | undefined = typeof globalThis !== 'undefined' ? globalThis : win\n\nexport const ArrayProto = Array.prototype\nexport const nativeForEach = ArrayProto.forEach\nexport const nativeIndexOf = ArrayProto.indexOf\n\nexport const navigator = global?.navigator\nexport const document = global?.document\nexport const location = global?.location\nexport const fetch = global?.fetch\nexport const XMLHttpRequest =\n global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined\nexport const AbortController = global?.AbortController\nexport const userAgent = navigator?.userAgent\nexport const assignableWindow: AssignableWindow = win ?? ({} as any)\n\nexport { win as window }\n"]}
1
+ {"version":3,"file":"globals.js","sourceRoot":"","sources":["../../../src/utils/globals.ts"],"names":[],"mappings":"AAYA;;;;;;;;GAQG;AAEH,iDAAiD;AACjD,IAAM,GAAG,GAA6C,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAA;AAmExG,IAAM,MAAM,GAAkC,OAAO,UAAU,KAAK,WAAW,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,GAAG,CAAA;AAElG,MAAM,CAAC,IAAM,UAAU,GAAG,KAAK,CAAC,SAAS,CAAA;AACzC,MAAM,CAAC,IAAM,aAAa,GAAG,UAAU,CAAC,OAAO,CAAA;AAC/C,MAAM,CAAC,IAAM,aAAa,GAAG,UAAU,CAAC,OAAO,CAAA;AAE/C,MAAM,CAAC,IAAM,SAAS,GAAG,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,SAAS,CAAA;AAC1C,MAAM,CAAC,IAAM,QAAQ,GAAG,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,QAAQ,CAAA;AACxC,MAAM,CAAC,IAAM,QAAQ,GAAG,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,QAAQ,CAAA;AACxC,MAAM,CAAC,IAAM,KAAK,GAAG,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,KAAK,CAAA;AAClC,MAAM,CAAC,IAAM,cAAc,GACvB,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,cAAc,KAAI,iBAAiB,IAAI,IAAI,MAAM,CAAC,cAAc,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS,CAAA;AAClH,MAAM,CAAC,IAAM,eAAe,GAAG,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,eAAe,CAAA;AACtD,MAAM,CAAC,IAAM,SAAS,GAAG,SAAS,aAAT,SAAS,uBAAT,SAAS,CAAE,SAAS,CAAA;AAC7C,MAAM,CAAC,IAAM,gBAAgB,GAAqB,GAAG,aAAH,GAAG,cAAH,GAAG,GAAK,EAAU,CAAA;AAEpE,OAAO,EAAE,GAAG,IAAI,MAAM,EAAE,CAAA","sourcesContent":["import { ErrorProperties } from '../extensions/exception-autocapture/error-conversion'\nimport type { PostHog } from '../posthog-core'\nimport { SessionIdManager } from '../sessionid'\nimport {\n DeadClicksAutoCaptureConfig,\n ErrorEventArgs,\n ErrorMetadata,\n Properties,\n RemoteConfig,\n SiteAppLoader,\n} from '../types'\n\n/*\n * Global helpers to protect access to browser globals in a way that is safer for different targets\n * like DOM, SSR, Web workers etc.\n *\n * NOTE: Typically we want the \"window\" but globalThis works for both the typical browser context as\n * well as other contexts such as the web worker context. Window is still exported for any bits that explicitly require it.\n * If in doubt - export the global you need from this file and use that as an optional value. This way the code path is forced\n * to handle the case where the global is not available.\n */\n\n// eslint-disable-next-line no-restricted-globals\nconst win: (Window & typeof globalThis) | undefined = typeof window !== 'undefined' ? window : undefined\n\nexport type AssignableWindow = Window &\n typeof globalThis &\n Record<string, any> & {\n __PosthogExtensions__?: PostHogExtensions\n _POSTHOG_CONFIG?: RemoteConfig\n _POSTHOG_JS_APPS?: SiteAppLoader[]\n }\n\n/**\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n * changes to this interface can be breaking changes for users of the SDK\n */\n\nexport type PostHogExtensionKind =\n | 'toolbar'\n | 'exception-autocapture'\n | 'web-vitals'\n | 'recorder'\n | 'tracing-headers'\n | 'surveys'\n | 'dead-clicks-autocapture'\n | 'remote-config'\n\nexport interface LazyLoadedDeadClicksAutocaptureInterface {\n start: (observerTarget: Node) => void\n stop: () => void\n}\n\ninterface PostHogExtensions {\n loadExternalDependency?: (\n posthog: PostHog,\n kind: PostHogExtensionKind,\n callback: (error?: string | Event, event?: Event) => void\n ) => void\n\n loadSiteApp?: (posthog: PostHog, appUrl: string, callback: (error?: string | Event, event?: Event) => void) => void\n\n parseErrorAsProperties?: (\n [event, source, lineno, colno, error]: ErrorEventArgs,\n metadata?: ErrorMetadata\n ) => ErrorProperties\n errorWrappingFunctions?: {\n wrapOnError: (captureFn: (props: Properties) => void) => () => void\n wrapUnhandledRejection: (captureFn: (props: Properties) => void) => () => void\n }\n rrweb?: { record: any; version: string }\n rrwebPlugins?: { getRecordConsolePlugin: any; getRecordNetworkPlugin?: any }\n canActivateRepeatedly?: (survey: any) => boolean\n generateSurveys?: (posthog: PostHog) => any | undefined\n postHogWebVitalsCallbacks?: {\n onLCP: (metric: any) => void\n onCLS: (metric: any) => void\n onFCP: (metric: any) => void\n onINP: (metric: any) => void\n }\n tracingHeadersPatchFns?: {\n _patchFetch: (sessionManager?: SessionIdManager) => () => void\n _patchXHR: (sessionManager?: SessionIdManager) => () => void\n }\n initDeadClicksAutocapture?: (\n ph: PostHog,\n config: DeadClicksAutoCaptureConfig\n ) => LazyLoadedDeadClicksAutocaptureInterface\n}\n\nconst global: typeof globalThis | undefined = typeof globalThis !== 'undefined' ? globalThis : win\n\nexport const ArrayProto = Array.prototype\nexport const nativeForEach = ArrayProto.forEach\nexport const nativeIndexOf = ArrayProto.indexOf\n\nexport const navigator = global?.navigator\nexport const document = global?.document\nexport const location = global?.location\nexport const fetch = global?.fetch\nexport const XMLHttpRequest =\n global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined\nexport const AbortController = global?.AbortController\nexport const userAgent = navigator?.userAgent\nexport const assignableWindow: AssignableWindow = win ?? ({} as any)\n\nexport { win as window }\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "posthog-js",
3
- "version": "1.200.0",
3
+ "version": "1.200.2",
4
4
  "description": "Posthog-js allows you to automatically capture usage and send events to PostHog.",
5
5
  "repository": "https://github.com/PostHog/posthog-js",
6
6
  "author": "hey@posthog.com",