posthog-js 1.90.2 → 1.91.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/array.full.js +1 -1
  2. package/dist/array.full.js.map +1 -1
  3. package/dist/array.js +1 -1
  4. package/dist/array.js.map +1 -1
  5. package/dist/es.js +1 -1
  6. package/dist/es.js.map +1 -1
  7. package/dist/exception-autocapture.js +1 -1
  8. package/dist/exception-autocapture.js.map +1 -1
  9. package/dist/module.d.ts +3 -4
  10. package/dist/module.js +1 -1
  11. package/dist/module.js.map +1 -1
  12. package/dist/recorder-v2.js +1 -1
  13. package/dist/recorder-v2.js.map +1 -1
  14. package/dist/recorder.js +1 -1
  15. package/dist/recorder.js.map +1 -1
  16. package/dist/surveys.js +1 -1
  17. package/dist/surveys.js.map +1 -1
  18. package/lib/package.json +1 -1
  19. package/lib/src/autocapture-utils.js +2 -1
  20. package/lib/src/autocapture-utils.js.map +1 -1
  21. package/lib/src/autocapture.js +11 -4
  22. package/lib/src/autocapture.js.map +1 -1
  23. package/lib/src/decide.js +2 -1
  24. package/lib/src/decide.js.map +1 -1
  25. package/lib/src/extensions/exception-autocapture/index.js +6 -3
  26. package/lib/src/extensions/exception-autocapture/index.js.map +1 -1
  27. package/lib/src/extensions/replay/sessionrecording.js +8 -8
  28. package/lib/src/extensions/replay/sessionrecording.js.map +1 -1
  29. package/lib/src/extensions/replay/web-performance.js +1 -0
  30. package/lib/src/extensions/replay/web-performance.js.map +1 -1
  31. package/lib/src/extensions/surveys.js +10 -2
  32. package/lib/src/extensions/surveys.js.map +1 -1
  33. package/lib/src/extensions/toolbar.d.ts +2 -2
  34. package/lib/src/extensions/toolbar.js +16 -13
  35. package/lib/src/extensions/toolbar.js.map +1 -1
  36. package/lib/src/gdpr-utils.js +2 -2
  37. package/lib/src/gdpr-utils.js.map +1 -1
  38. package/lib/src/loader-exception-autocapture.js +4 -3
  39. package/lib/src/loader-exception-autocapture.js.map +1 -1
  40. package/lib/src/loader-recorder-v2.js +7 -4
  41. package/lib/src/loader-recorder-v2.js.map +1 -1
  42. package/lib/src/loader-recorder.js +6 -6
  43. package/lib/src/loader-recorder.js.map +1 -1
  44. package/lib/src/loader-surveys.js +5 -3
  45. package/lib/src/loader-surveys.js.map +1 -1
  46. package/lib/src/page-view.js +14 -11
  47. package/lib/src/page-view.js.map +1 -1
  48. package/lib/src/posthog-core.js +21 -22
  49. package/lib/src/posthog-core.js.map +1 -1
  50. package/lib/src/posthog-surveys.js +7 -4
  51. package/lib/src/posthog-surveys.js.map +1 -1
  52. package/lib/src/retry-queue.js +2 -1
  53. package/lib/src/retry-queue.js.map +1 -1
  54. package/lib/src/session-props.d.ts +1 -2
  55. package/lib/src/session-props.js +2 -2
  56. package/lib/src/session-props.js.map +1 -1
  57. package/lib/src/sessionid.js +1 -1
  58. package/lib/src/sessionid.js.map +1 -1
  59. package/lib/src/storage.d.ts +1 -1
  60. package/lib/src/storage.js +18 -8
  61. package/lib/src/storage.js.map +1 -1
  62. package/lib/src/utils/event-utils.js +16 -10
  63. package/lib/src/utils/event-utils.js.map +1 -1
  64. package/lib/src/utils/globals.d.ts +5 -4
  65. package/lib/src/utils/globals.js +7 -5
  66. package/lib/src/utils/globals.js.map +1 -1
  67. package/lib/src/utils/index.js +7 -4
  68. package/lib/src/utils/index.js.map +1 -1
  69. package/lib/src/utils/logger.js +5 -2
  70. package/lib/src/utils/logger.js.map +1 -1
  71. package/lib/src/uuidv7.js +1 -1
  72. package/lib/src/uuidv7.js.map +1 -1
  73. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"sessionrecording.js","sourceRoot":"","sources":["../../../../src/extensions/replay/sessionrecording.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EACH,yCAAyC,EACzC,qCAAqC,EACrC,4BAA4B,EAC5B,yCAAyC,EACzC,8CAA8C,GACjD,MAAM,iBAAiB,C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QAAQ,CAAA;SACvC;QAED,IAAI,CAAC,MAAM,CAAC,IAAI,IAAI,UAAU,CAAC,eAAe,CAAA;QAC9C,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,CAAA;QAEhD,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE;YACxB,IAAI,CAAC,gBAAgB,GAAG,UAAU,CAAC;gBAC/B,KAAI,CAAC,YAAY,EAAE,CAAA;YACvB,CAAC,EAAE,wBAAwB,CAAC,CAAA;SAC/B;IACL,CAAC;IAEO,2CAAgB,GAAxB,UAAyB,UAAsB;QAC3C,oGAAoG;QACpG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,WAAW,EAAE,UAAU,EAAE;YAC3C,SAAS,EAAE,KAAK;YAChB,MAAM,EAAE,MAAM;YACd,QAAQ,EAAE,IAAI,CAAC,SAAS;YACxB,WAAW,EAAE,IAAI;YACjB,SAAS,EAAE,2BAA2B;YACtC,QAAQ,EAAE;gBACN,mBAAmB,EAAE,UAAU,CAAC,cAAc,CAAC,IAAI,KAAK,wBAAwB;aACnF;SACJ,CAAC,CAAA;IACN,CAAC;IACL,uBAAC;AAAD,CAAC,AAplBD,IAolBC","sourcesContent":["import {\n CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_IS_SAMPLED,\n SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE,\n SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE,\n} from '../../constants'\nimport {\n FULL_SNAPSHOT_EVENT_TYPE,\n INCREMENTAL_SNAPSHOT_EVENT_TYPE,\n META_EVENT_TYPE,\n MutationRateLimiter,\n recordOptions,\n rrwebRecord,\n truncateLargeConsoleLogs,\n} from './sessionrecording-utils'\nimport { PostHog } from '../../posthog-core'\nimport { DecideResponse, NetworkRecordOptions, NetworkRequest, Properties } from '../../types'\nimport { EventType, type eventWithTime, type listenerHandler } from '@rrweb/types'\nimport Config from '../../config'\nimport { _timestamp, loadScript } from '../../utils'\n\nimport { _isBoolean, _isFunction, _isNull, _isNumber, _isObject, _isString, _isUndefined } from '../../utils/type-utils'\nimport { logger } from '../../utils/logger'\nimport { window } from '../../utils/globals'\nimport { buildNetworkRequestOptions } from './config'\n\nconst BASE_ENDPOINT = '/s/'\n\nexport const RECORDING_IDLE_ACTIVITY_TIMEOUT_MS = 5 * 60 * 1000 // 5 minutes\nexport const RECORDING_MAX_EVENT_SIZE = 1024 * 1024 * 0.9 // ~1mb (with some wiggle room)\nexport const RECORDING_BUFFER_TIMEOUT = 2000 // 2 seconds\nexport const SESSION_RECORDING_BATCH_KEY = 'recordings'\n\n// NOTE: Importing this type is problematic as we can't safely bundle it to a TS definition so, instead we redefine.\n// import type { record } from 'rrweb2/typings'\n// import type { recordOptions } from 'rrweb/typings/types'\n\n// Copied from rrweb typings to avoid import\nenum IncrementalSource {\n Mutation = 0,\n MouseMove = 1,\n MouseInteraction = 2,\n Scroll = 3,\n ViewportResize = 4,\n Input = 5,\n TouchMove = 6,\n MediaInteraction = 7,\n StyleSheetRule = 8,\n CanvasMutation = 9,\n Font = 10,\n Log = 11,\n Drag = 12,\n StyleDeclaration = 13,\n Selection = 14,\n AdoptedStyleSheet = 15,\n}\n\nconst ACTIVE_SOURCES = [\n IncrementalSource.MouseMove,\n IncrementalSource.MouseInteraction,\n IncrementalSource.Scroll,\n IncrementalSource.ViewportResize,\n IncrementalSource.Input,\n IncrementalSource.TouchMove,\n IncrementalSource.MediaInteraction,\n IncrementalSource.Drag,\n]\n\n/**\n * Session recording starts in buffering mode while waiting for decide response\n * Once the response is received it might be disabled, active or sampled\n * When sampled that means a sample rate is set and the last time the session id was rotated\n * the sample rate determined this session should be sent to the server.\n */\ntype SessionRecordingStatus = 'disabled' | 'sampled' | 'active' | 'buffering'\n\ninterface SnapshotBuffer {\n size: number\n data: any[]\n sessionId: string | null\n windowId: string | null\n}\n\nexport class SessionRecording {\n private instance: PostHog\n private _endpoint: string\n private flushBufferTimer?: any\n private buffer?: SnapshotBuffer\n private mutationRateLimiter?: MutationRateLimiter\n private _captureStarted: boolean\n private stopRrweb: listenerHandler | undefined\n private receivedDecide: boolean\n private rrwebRecord: rrwebRecord | undefined\n private isIdle = false\n\n private _linkedFlagSeen: boolean = false\n private _lastActivityTimestamp: number = Date.now()\n private windowId: string | null = null\n private sessionId: string | null = null\n private _linkedFlag: string | null = null\n private _sampleRate: number | null = null\n private _minimumDuration: number | null = null\n\n public get started(): boolean {\n // TODO could we use status instead of _captureStarted?\n return this._captureStarted\n }\n\n private get sessionManager() {\n if (!this.instance.sessionManager) {\n logger.error('Session recording started without valid sessionManager')\n throw new Error('Session recording started without valid sessionManager. This is a bug.')\n }\n\n return this.instance.sessionManager\n }\n\n private get isSampled(): boolean | null {\n if (_isNumber(this._sampleRate)) {\n return this.instance.get_property(SESSION_RECORDING_IS_SAMPLED)\n } else {\n return null\n }\n }\n\n private get sessionDuration(): number | null {\n const mostRecentSnapshot = this.buffer?.data[this.buffer?.data.length - 1]\n const { sessionStartTimestamp } = this.sessionManager.checkAndGetSessionAndWindowId(true)\n return mostRecentSnapshot ? mostRecentSnapshot.timestamp - sessionStartTimestamp : null\n }\n\n private get isRecordingEnabled() {\n const enabled_server_side = !!this.instance.get_property(SESSION_RECORDING_ENABLED_SERVER_SIDE)\n const enabled_client_side = !this.instance.config.disable_session_recording\n return enabled_server_side && enabled_client_side\n }\n\n private get isConsoleLogCaptureEnabled() {\n const enabled_server_side = !!this.instance.get_property(CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE)\n const enabled_client_side = this.instance.config.enable_recording_console_log\n return enabled_client_side ?? enabled_server_side\n }\n\n private get recordingVersion() {\n const recordingVersion_server_side = this.instance.get_property(SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE)\n const recordingVersion_client_side = this.instance.config.session_recording?.recorderVersion\n return recordingVersion_client_side || recordingVersion_server_side || 'v1'\n }\n\n private get networkPayloadCapture(): Pick<NetworkRecordOptions, 'recordHeaders' | 'recordBody'> | undefined {\n const networkPayloadCapture_server_side = this.instance.get_property(SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE)\n const networkPayloadCapture_client_side = {\n recordHeaders: this.instance.config.session_recording?.recordHeaders,\n recordBody: this.instance.config.session_recording?.recordBody,\n }\n const headersEnabled =\n networkPayloadCapture_client_side?.recordHeaders || networkPayloadCapture_server_side?.recordHeaders\n const bodyEnabled =\n networkPayloadCapture_client_side?.recordBody || networkPayloadCapture_server_side?.recordBody\n return headersEnabled || bodyEnabled ? { recordHeaders: headersEnabled, recordBody: bodyEnabled } : undefined\n }\n\n /**\n * defaults to buffering mode until a decide response is received\n * once a decide response is received status can be disabled, active or sampled\n */\n private get status(): SessionRecordingStatus {\n if (!this.receivedDecide) {\n return 'buffering'\n }\n\n if (!this.isRecordingEnabled) {\n return 'disabled'\n }\n\n if (_isString(this._linkedFlag) && !this._linkedFlagSeen) {\n return 'buffering'\n }\n\n if (_isBoolean(this.isSampled)) {\n return this.isSampled ? 'sampled' : 'disabled'\n } else {\n return 'active'\n }\n }\n\n constructor(instance: PostHog) {\n this.instance = instance\n this._captureStarted = false\n this._endpoint = BASE_ENDPOINT\n this.stopRrweb = undefined\n this.receivedDecide = false\n\n window.addEventListener('beforeunload', () => {\n this._flushBuffer()\n })\n\n if (!this.instance.sessionManager) {\n logger.error('Session recording started without valid sessionManager')\n throw new Error('Session recording started without valid sessionManager. This is a bug.')\n }\n\n this.buffer = this.clearBuffer()\n }\n\n startRecordingIfEnabled() {\n if (this.isRecordingEnabled) {\n this.startCaptureAndTrySendingQueuedSnapshots()\n } else {\n this.stopRecording()\n this.clearBuffer()\n }\n }\n\n stopRecording() {\n if (this._captureStarted && this.stopRrweb) {\n this.stopRrweb()\n this.stopRrweb = undefined\n this._captureStarted = false\n }\n }\n\n private makeSamplingDecision(sessionId: string): void {\n const sessionIdChanged = this.sessionId !== sessionId\n\n if (!_isNumber(this._sampleRate)) {\n this.instance.persistence?.register({\n [SESSION_RECORDING_IS_SAMPLED]: null,\n })\n return\n }\n\n const storedIsSampled = this.isSampled\n\n /**\n * if we get this far then we should make a sampling decision.\n * When the session id changes or there is no stored sampling decision for this session id\n * then we should make a new decision.\n *\n * Otherwise, we should use the stored decision.\n */\n let shouldSample: boolean\n if (sessionIdChanged || !_isBoolean(storedIsSampled)) {\n const randomNumber = Math.random()\n shouldSample = randomNumber < this._sampleRate\n } else {\n shouldSample = storedIsSampled\n }\n\n if (!shouldSample) {\n logger.warn(\n `[SessionSampling] Sample rate (${this._sampleRate}) has determined that this sessionId (${sessionId}) will not be sent to the server.`\n )\n }\n\n this.instance.persistence?.register({\n [SESSION_RECORDING_IS_SAMPLED]: shouldSample,\n })\n }\n\n afterDecideResponse(response: DecideResponse) {\n if (this.instance.persistence) {\n this.instance.persistence.register({\n [SESSION_RECORDING_ENABLED_SERVER_SIDE]: !!response['sessionRecording'],\n [CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE]: response.sessionRecording?.consoleLogRecordingEnabled,\n [SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE]: response.sessionRecording?.recorderVersion,\n [SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE]: response.sessionRecording?.networkPayloadCapture,\n })\n }\n\n const receivedSampleRate = response.sessionRecording?.sampleRate\n this._sampleRate =\n _isUndefined(receivedSampleRate) || _isNull(receivedSampleRate) ? null : parseFloat(receivedSampleRate)\n\n const receivedMinimumDuration = response.sessionRecording?.minimumDurationMilliseconds\n this._minimumDuration = _isUndefined(receivedMinimumDuration) ? null : receivedMinimumDuration\n\n this._linkedFlag = response.sessionRecording?.linkedFlag || null\n\n if (response.sessionRecording?.endpoint) {\n this._endpoint = response.sessionRecording?.endpoint\n }\n\n if (_isNumber(this._sampleRate)) {\n this.sessionManager.onSessionId((sessionId) => {\n this.makeSamplingDecision(sessionId)\n })\n }\n\n if (_isString(this._linkedFlag)) {\n const linkedFlag = this._linkedFlag\n this.instance.onFeatureFlags((flags) => {\n this._linkedFlagSeen = flags.includes(linkedFlag)\n })\n }\n\n this.receivedDecide = true\n this.startRecordingIfEnabled()\n }\n\n log(message: string, level: 'log' | 'warn' | 'error' = 'log') {\n this.instance.sessionRecording?.onRRwebEmit({\n type: 6,\n data: {\n plugin: 'rrweb/console@1',\n payload: {\n level,\n trace: [],\n // Even though it is a string we stringify it as that's what rrweb expects\n payload: [JSON.stringify(message)],\n },\n },\n timestamp: _timestamp(),\n })\n }\n\n private startCaptureAndTrySendingQueuedSnapshots() {\n this._startCapture()\n }\n\n private _startCapture() {\n if (_isUndefined(Object.assign)) {\n // According to the rrweb docs, rrweb is not supported on IE11 and below:\n // \"rrweb does not support IE11 and below because it uses the MutationObserver API which was supported by these browsers.\"\n // https://github.com/rrweb-io/rrweb/blob/master/guide.md#compatibility-note\n //\n // However, MutationObserver does exist on IE11, it just doesn't work well and does not detect all changes.\n // Instead, when we load \"recorder.js\", the first JS error is about \"Object.assign\" being undefined.\n // Thus instead of MutationObserver, we look for this function and block recording if it's undefined.\n return\n }\n\n // We do not switch recorder versions midway through a recording.\n if (this._captureStarted || this.instance.config.disable_session_recording) {\n return\n }\n\n this._captureStarted = true\n // We want to ensure the sessionManager is reset if necessary on load of the recorder\n this.sessionManager.checkAndGetSessionAndWindowId()\n\n const recorderJS = this.recordingVersion === 'v2' ? 'recorder-v2.js' : 'recorder.js'\n\n // If recorder.js is already loaded (if array.full.js snippet is used or posthog-js/dist/recorder is\n // imported) or matches the requested recorder version, don't load script. Otherwise, remotely import\n // recorder.js from cdn since it hasn't been loaded.\n if (this.instance.__loaded_recorder_version !== this.recordingVersion) {\n loadScript(this.instance.config.api_host + `/static/${recorderJS}?v=${Config.LIB_VERSION}`, (err) => {\n if (err) {\n return logger.error(`Could not load ${recorderJS}`, err)\n }\n\n this._onScriptLoaded()\n })\n } else {\n this._onScriptLoaded()\n }\n }\n\n private _isInteractiveEvent(event: eventWithTime) {\n return event.type === INCREMENTAL_SNAPSHOT_EVENT_TYPE && ACTIVE_SOURCES.indexOf(event.data?.source) !== -1\n }\n\n private _updateWindowAndSessionIds(event: eventWithTime) {\n // Some recording events are triggered by non-user events (e.g. \"X minutes ago\" text updating on the screen).\n // We don't want to extend the session or trigger a new session in these cases. These events are designated by event\n // type -> incremental update, and source -> mutation.\n\n const isUserInteraction = this._isInteractiveEvent(event)\n\n if (!isUserInteraction && !this.isIdle) {\n // We check if the lastActivityTimestamp is old enough to go idle\n if (event.timestamp - this._lastActivityTimestamp > RECORDING_IDLE_ACTIVITY_TIMEOUT_MS) {\n this.isIdle = true\n }\n }\n\n if (isUserInteraction) {\n this._lastActivityTimestamp = event.timestamp\n if (this.isIdle) {\n // Remove the idle state if set and trigger a full snapshot as we will have ignored previous mutations\n this.isIdle = false\n this._tryTakeFullSnapshot()\n }\n }\n\n if (this.isIdle) {\n return\n }\n\n // We only want to extend the session if it is an interactive event.\n const { windowId, sessionId } = this.sessionManager.checkAndGetSessionAndWindowId(\n !isUserInteraction,\n event.timestamp\n )\n\n const sessionIdChanged = this.sessionId !== sessionId\n const windowIdChanged = this.windowId !== windowId\n\n if (\n [FULL_SNAPSHOT_EVENT_TYPE, META_EVENT_TYPE].indexOf(event.type) === -1 &&\n (windowIdChanged || sessionIdChanged)\n ) {\n this._tryTakeFullSnapshot()\n }\n\n this.windowId = windowId\n this.sessionId = sessionId\n }\n\n private _tryTakeFullSnapshot(): boolean {\n // TODO this should ignore based on emit?\n if (!this._captureStarted) {\n return false\n }\n try {\n this.rrwebRecord?.takeFullSnapshot()\n return true\n } catch (e) {\n // Sometimes a race can occur where the recorder is not fully started yet, so we can't take a full snapshot.\n logger.error('Error taking full snapshot.', e)\n return false\n }\n }\n\n private _onScriptLoaded() {\n // rrweb config info: https://github.com/rrweb-io/rrweb/blob/7d5d0033258d6c29599fb08412202d9a2c7b9413/src/record/index.ts#L28\n const sessionRecordingOptions: recordOptions<eventWithTime> = {\n // select set of rrweb config options we expose to our users\n // see https://github.com/rrweb-io/rrweb/blob/master/guide.md\n blockClass: 'ph-no-capture',\n blockSelector: undefined,\n ignoreClass: 'ph-ignore-input',\n maskTextClass: 'ph-mask',\n maskTextSelector: undefined,\n maskTextFn: undefined,\n maskAllInputs: true,\n maskInputOptions: {},\n maskInputFn: undefined,\n slimDOMOptions: {},\n collectFonts: false,\n inlineStylesheet: true,\n recordCrossOriginIframes: false,\n }\n // We switched from loading all of rrweb to just the record part, but\n // keep backwards compatibility if someone hasn't upgraded PostHog\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.rrwebRecord = window.rrweb ? window.rrweb.record : window.rrwebRecord\n\n // only allows user to set our allow-listed options\n const userSessionRecordingOptions = this.instance.config.session_recording\n for (const [key, value] of Object.entries(userSessionRecordingOptions || {})) {\n if (key in sessionRecordingOptions) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n sessionRecordingOptions[key] = value\n }\n }\n\n if (!this.rrwebRecord) {\n logger.error(\n 'onScriptLoaded was called but rrwebRecord is not available. This indicates something has gone wrong.'\n )\n return\n }\n\n this.mutationRateLimiter =\n this.mutationRateLimiter ??\n new MutationRateLimiter(this.rrwebRecord, {\n onBlockedNode: (id, node) => {\n const message = `Too many mutations on node '${id}'. Rate limiting. This could be due to SVG animations or something similar`\n logger.info(message, {\n node: node,\n })\n\n this.log('[PostHog Recorder] ' + message, 'warn')\n },\n })\n\n const plugins = []\n\n if ((window as any).rrwebConsoleRecord && this.isConsoleLogCaptureEnabled) {\n plugins.push((window as any).rrwebConsoleRecord.getRecordConsolePlugin())\n }\n if (this.networkPayloadCapture && _isFunction((window as any).getRecordNetworkPlugin)) {\n plugins.push(\n (window as any).getRecordNetworkPlugin(\n buildNetworkRequestOptions(this.instance.config, this.networkPayloadCapture)\n )\n )\n }\n\n this.stopRrweb = this.rrwebRecord({\n emit: (event) => {\n this.onRRwebEmit(event)\n },\n plugins,\n ...sessionRecordingOptions,\n })\n\n // :TRICKY: rrweb does not capture navigation within SPA-s, so hook into our $pageview events to get access to all events.\n // Dropping the initial event is fine (it's always captured by rrweb).\n this.instance._addCaptureHook((eventName) => {\n // If anything could go wrong here it has the potential to block the main loop,\n // so we catch all errors.\n try {\n if (eventName === '$pageview') {\n const href = this._maskUrl(window.location.href)\n if (!href) {\n return\n }\n this.rrwebRecord?.addCustomEvent('$pageview', { href })\n }\n } catch (e) {\n logger.error('Could not add $pageview to rrweb session', e)\n }\n })\n\n // We reset the last activity timestamp, resetting the idle timer\n this._lastActivityTimestamp = Date.now()\n this.isIdle = false\n }\n\n onRRwebEmit(rawEvent: eventWithTime) {\n if (!rawEvent || !_isObject(rawEvent)) {\n return\n }\n\n if (rawEvent.type === EventType.Meta) {\n const href = this._maskUrl(rawEvent.data.href)\n if (!href) {\n return\n }\n rawEvent.data.href = href\n }\n\n const throttledEvent = this.mutationRateLimiter\n ? this.mutationRateLimiter.throttleMutations(rawEvent)\n : rawEvent\n\n if (!throttledEvent) {\n return\n }\n\n // TODO: Re-add ensureMaxMessageSize once we are confident in it\n const event = truncateLargeConsoleLogs(throttledEvent)\n const size = JSON.stringify(event).length\n\n this._updateWindowAndSessionIds(event)\n\n if (this.isIdle) {\n // When in an idle state we keep recording, but don't capture the events\n return\n }\n\n const properties = {\n $snapshot_bytes: size,\n $snapshot_data: event,\n $session_id: this.sessionId,\n $window_id: this.windowId,\n }\n\n if (this.status !== 'disabled') {\n this._captureSnapshotBuffered(properties)\n } else {\n this.clearBuffer()\n }\n }\n\n private _maskUrl(url: string): string | undefined {\n const userSessionRecordingOptions = this.instance.config.session_recording\n\n if (userSessionRecordingOptions.maskNetworkRequestFn) {\n let networkRequest: NetworkRequest | null | undefined = {\n url,\n }\n\n // TODO we should deprecate this and use the same function for this masking and the rrweb/network plugin\n // TODO or deprecate this and provide a new clearer name so this would be `maskURLPerformanceFn` or similar\n networkRequest = userSessionRecordingOptions.maskNetworkRequestFn(networkRequest)\n\n return networkRequest?.url\n }\n\n return url\n }\n\n private clearBuffer(): SnapshotBuffer {\n this.buffer = undefined\n\n return {\n size: 0,\n data: [],\n sessionId: this.sessionId,\n windowId: this.windowId,\n }\n }\n\n // the intention is a buffer that (currently) is used only after a decide response enables session recording\n // it is called ever X seconds using the flushBufferTimer so that we don't have to wait for the buffer to fill up\n // when it is called on a timer it assumes that it can definitely flush\n // it is flushed when the session id changes or the size of the buffered data gets too great (1mb by default)\n // first change: if the recording is in buffering mode,\n // flush buffer simply resets the timer and returns the existing flush buffer\n private _flushBuffer() {\n if (this.flushBufferTimer) {\n clearTimeout(this.flushBufferTimer)\n this.flushBufferTimer = undefined\n }\n\n const minimumDuration = this._minimumDuration\n const sessionDuration = this.sessionDuration\n // if we have old data in the buffer but the session has rotated then the\n // session duration might be negative, in that case we want to flush the buffer\n const isPositiveSessionDuration = _isNumber(sessionDuration) && sessionDuration >= 0\n const isBelowMinimumDuration =\n _isNumber(minimumDuration) && isPositiveSessionDuration && sessionDuration < minimumDuration\n\n if (this.status === 'buffering' || isBelowMinimumDuration) {\n this.flushBufferTimer = setTimeout(() => {\n this._flushBuffer()\n }, RECORDING_BUFFER_TIMEOUT)\n return this.buffer || this.clearBuffer()\n }\n\n if (this.buffer && this.buffer.data.length !== 0) {\n this._captureSnapshot({\n $snapshot_bytes: this.buffer.size,\n $snapshot_data: this.buffer.data,\n $session_id: this.buffer.sessionId,\n $window_id: this.buffer.windowId,\n })\n\n return this.clearBuffer()\n } else {\n return this.buffer || this.clearBuffer()\n }\n }\n\n private _captureSnapshotBuffered(properties: Properties) {\n const additionalBytes = 2 + (this.buffer?.data.length || 0) // 2 bytes for the array brackets and 1 byte for each comma\n if (\n !this.buffer ||\n this.buffer.size + properties.$snapshot_bytes + additionalBytes > RECORDING_MAX_EVENT_SIZE ||\n (!!this.buffer.sessionId && this.buffer.sessionId !== this.sessionId)\n ) {\n this.buffer = this._flushBuffer()\n }\n\n if (_isNull(this.buffer.sessionId) && !_isNull(this.sessionId)) {\n // session id starts null but has now been assigned, update the buffer\n this.buffer.sessionId = this.sessionId\n this.buffer.windowId = this.windowId\n }\n\n this.buffer.size += properties.$snapshot_bytes\n this.buffer.data.push(properties.$snapshot_data)\n\n if (!this.flushBufferTimer) {\n this.flushBufferTimer = setTimeout(() => {\n this._flushBuffer()\n }, RECORDING_BUFFER_TIMEOUT)\n }\n }\n\n private _captureSnapshot(properties: Properties) {\n // :TRICKY: Make sure we batch these requests, use a custom endpoint and don't truncate the strings.\n this.instance.capture('$snapshot', properties, {\n transport: 'XHR',\n method: 'POST',\n endpoint: this._endpoint,\n _noTruncate: true,\n _batchKey: SESSION_RECORDING_BATCH_KEY,\n _metrics: {\n rrweb_full_snapshot: properties.$snapshot_data.type === FULL_SNAPSHOT_EVENT_TYPE,\n },\n })\n }\n}\n"]}
1
+ {"version":3,"file":"sessionrecording.js","sourceRoot":"","sources":["../../../../src/extensions/replay/sessionrecording.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EACH,yCAAyC,EACzC,qCAAqC,EACrC,4BAA4B,EAC5B,yCAAyC,EACzC,8CAA8C,GACjD,MAAM,iBAAiB,CAAA;AACxB,OAAO,EACH,wBAAwB,EACxB,+BAA+B,EAC/B,eAAe,EACf,mBAAmB,EAGnB,wBAAwB,GAC3B,MAAM,0BAA0B,CAAA;AAGjC,OAAO,EAAE,SAAS,EAA4C,MAAM,cAAc,CAAA;AAClF,OAAO,MAAM,MAAM,cAAc,CAAA;AACjC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAEpD,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAA;AACxH,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AAC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C3C,oGAAoG;QACpG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,WAAW,EAAE,UAAU,EAAE;YAC3C,SAAS,EAAE,KAAK;YAChB,MAAM,EAAE,MAAM;YACd,QAAQ,EAAE,IAAI,CAAC,SAAS;YACxB,WAAW,EAAE,IAAI;YACjB,SAAS,EAAE,2BAA2B;YACtC,QAAQ,EAAE;gBACN,mBAAmB,EAAE,UAAU,CAAC,cAAc,CAAC,IAAI,KAAK,wBAAwB;aACnF;SACJ,CAAC,CAAA;IACN,CAAC;IACL,uBAAC;AAAD,CAAC,AAplBD,IAolBC","sourcesContent":["import {\n CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_IS_SAMPLED,\n SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE,\n SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE,\n} from '../../constants'\nimport {\n FULL_SNAPSHOT_EVENT_TYPE,\n INCREMENTAL_SNAPSHOT_EVENT_TYPE,\n META_EVENT_TYPE,\n MutationRateLimiter,\n recordOptions,\n rrwebRecord,\n truncateLargeConsoleLogs,\n} from './sessionrecording-utils'\nimport { PostHog } from '../../posthog-core'\nimport { DecideResponse, NetworkRecordOptions, NetworkRequest, Properties } from '../../types'\nimport { EventType, type eventWithTime, type listenerHandler } from '@rrweb/types'\nimport Config from '../../config'\nimport { _timestamp, loadScript } from '../../utils'\n\nimport { _isBoolean, _isFunction, _isNull, _isNumber, _isObject, _isString, _isUndefined } from '../../utils/type-utils'\nimport { logger } from '../../utils/logger'\nimport { assignableWindow, window } from '../../utils/globals'\nimport { buildNetworkRequestOptions } from './config'\n\nconst BASE_ENDPOINT = '/s/'\n\nexport const RECORDING_IDLE_ACTIVITY_TIMEOUT_MS = 5 * 60 * 1000 // 5 minutes\nexport const RECORDING_MAX_EVENT_SIZE = 1024 * 1024 * 0.9 // ~1mb (with some wiggle room)\nexport const RECORDING_BUFFER_TIMEOUT = 2000 // 2 seconds\nexport const SESSION_RECORDING_BATCH_KEY = 'recordings'\n\n// NOTE: Importing this type is problematic as we can't safely bundle it to a TS definition so, instead we redefine.\n// import type { record } from 'rrweb2/typings'\n// import type { recordOptions } from 'rrweb/typings/types'\n\n// Copied from rrweb typings to avoid import\nenum IncrementalSource {\n Mutation = 0,\n MouseMove = 1,\n MouseInteraction = 2,\n Scroll = 3,\n ViewportResize = 4,\n Input = 5,\n TouchMove = 6,\n MediaInteraction = 7,\n StyleSheetRule = 8,\n CanvasMutation = 9,\n Font = 10,\n Log = 11,\n Drag = 12,\n StyleDeclaration = 13,\n Selection = 14,\n AdoptedStyleSheet = 15,\n}\n\nconst ACTIVE_SOURCES = [\n IncrementalSource.MouseMove,\n IncrementalSource.MouseInteraction,\n IncrementalSource.Scroll,\n IncrementalSource.ViewportResize,\n IncrementalSource.Input,\n IncrementalSource.TouchMove,\n IncrementalSource.MediaInteraction,\n IncrementalSource.Drag,\n]\n\n/**\n * Session recording starts in buffering mode while waiting for decide response\n * Once the response is received it might be disabled, active or sampled\n * When sampled that means a sample rate is set and the last time the session id was rotated\n * the sample rate determined this session should be sent to the server.\n */\ntype SessionRecordingStatus = 'disabled' | 'sampled' | 'active' | 'buffering'\n\ninterface SnapshotBuffer {\n size: number\n data: any[]\n sessionId: string | null\n windowId: string | null\n}\n\nexport class SessionRecording {\n private instance: PostHog\n private _endpoint: string\n private flushBufferTimer?: any\n private buffer?: SnapshotBuffer\n private mutationRateLimiter?: MutationRateLimiter\n private _captureStarted: boolean\n private stopRrweb: listenerHandler | undefined\n private receivedDecide: boolean\n private rrwebRecord: rrwebRecord | undefined\n private isIdle = false\n\n private _linkedFlagSeen: boolean = false\n private _lastActivityTimestamp: number = Date.now()\n private windowId: string | null = null\n private sessionId: string | null = null\n private _linkedFlag: string | null = null\n private _sampleRate: number | null = null\n private _minimumDuration: number | null = null\n\n public get started(): boolean {\n // TODO could we use status instead of _captureStarted?\n return this._captureStarted\n }\n\n private get sessionManager() {\n if (!this.instance.sessionManager) {\n logger.error('Session recording started without valid sessionManager')\n throw new Error('Session recording started without valid sessionManager. This is a bug.')\n }\n\n return this.instance.sessionManager\n }\n\n private get isSampled(): boolean | null {\n if (_isNumber(this._sampleRate)) {\n return this.instance.get_property(SESSION_RECORDING_IS_SAMPLED)\n } else {\n return null\n }\n }\n\n private get sessionDuration(): number | null {\n const mostRecentSnapshot = this.buffer?.data[this.buffer?.data.length - 1]\n const { sessionStartTimestamp } = this.sessionManager.checkAndGetSessionAndWindowId(true)\n return mostRecentSnapshot ? mostRecentSnapshot.timestamp - sessionStartTimestamp : null\n }\n\n private get isRecordingEnabled() {\n const enabled_server_side = !!this.instance.get_property(SESSION_RECORDING_ENABLED_SERVER_SIDE)\n const enabled_client_side = !this.instance.config.disable_session_recording\n return window && enabled_server_side && enabled_client_side\n }\n\n private get isConsoleLogCaptureEnabled() {\n const enabled_server_side = !!this.instance.get_property(CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE)\n const enabled_client_side = this.instance.config.enable_recording_console_log\n return enabled_client_side ?? enabled_server_side\n }\n\n private get recordingVersion() {\n const recordingVersion_server_side = this.instance.get_property(SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE)\n const recordingVersion_client_side = this.instance.config.session_recording?.recorderVersion\n return recordingVersion_client_side || recordingVersion_server_side || 'v1'\n }\n\n private get networkPayloadCapture(): Pick<NetworkRecordOptions, 'recordHeaders' | 'recordBody'> | undefined {\n const networkPayloadCapture_server_side = this.instance.get_property(SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE)\n const networkPayloadCapture_client_side = {\n recordHeaders: this.instance.config.session_recording?.recordHeaders,\n recordBody: this.instance.config.session_recording?.recordBody,\n }\n const headersEnabled =\n networkPayloadCapture_client_side?.recordHeaders || networkPayloadCapture_server_side?.recordHeaders\n const bodyEnabled =\n networkPayloadCapture_client_side?.recordBody || networkPayloadCapture_server_side?.recordBody\n return headersEnabled || bodyEnabled ? { recordHeaders: headersEnabled, recordBody: bodyEnabled } : undefined\n }\n\n /**\n * defaults to buffering mode until a decide response is received\n * once a decide response is received status can be disabled, active or sampled\n */\n private get status(): SessionRecordingStatus {\n if (!this.receivedDecide) {\n return 'buffering'\n }\n\n if (!this.isRecordingEnabled) {\n return 'disabled'\n }\n\n if (_isString(this._linkedFlag) && !this._linkedFlagSeen) {\n return 'buffering'\n }\n\n if (_isBoolean(this.isSampled)) {\n return this.isSampled ? 'sampled' : 'disabled'\n } else {\n return 'active'\n }\n }\n\n constructor(instance: PostHog) {\n this.instance = instance\n this._captureStarted = false\n this._endpoint = BASE_ENDPOINT\n this.stopRrweb = undefined\n this.receivedDecide = false\n\n window?.addEventListener('beforeunload', () => {\n this._flushBuffer()\n })\n\n if (!this.instance.sessionManager) {\n logger.error('Session recording started without valid sessionManager')\n throw new Error('Session recording started without valid sessionManager. This is a bug.')\n }\n\n this.buffer = this.clearBuffer()\n }\n\n startRecordingIfEnabled() {\n if (this.isRecordingEnabled) {\n this.startCaptureAndTrySendingQueuedSnapshots()\n } else {\n this.stopRecording()\n this.clearBuffer()\n }\n }\n\n stopRecording() {\n if (this._captureStarted && this.stopRrweb) {\n this.stopRrweb()\n this.stopRrweb = undefined\n this._captureStarted = false\n }\n }\n\n private makeSamplingDecision(sessionId: string): void {\n const sessionIdChanged = this.sessionId !== sessionId\n\n if (!_isNumber(this._sampleRate)) {\n this.instance.persistence?.register({\n [SESSION_RECORDING_IS_SAMPLED]: null,\n })\n return\n }\n\n const storedIsSampled = this.isSampled\n\n /**\n * if we get this far then we should make a sampling decision.\n * When the session id changes or there is no stored sampling decision for this session id\n * then we should make a new decision.\n *\n * Otherwise, we should use the stored decision.\n */\n let shouldSample: boolean\n if (sessionIdChanged || !_isBoolean(storedIsSampled)) {\n const randomNumber = Math.random()\n shouldSample = randomNumber < this._sampleRate\n } else {\n shouldSample = storedIsSampled\n }\n\n if (!shouldSample) {\n logger.warn(\n `[SessionSampling] Sample rate (${this._sampleRate}) has determined that this sessionId (${sessionId}) will not be sent to the server.`\n )\n }\n\n this.instance.persistence?.register({\n [SESSION_RECORDING_IS_SAMPLED]: shouldSample,\n })\n }\n\n afterDecideResponse(response: DecideResponse) {\n if (this.instance.persistence) {\n this.instance.persistence.register({\n [SESSION_RECORDING_ENABLED_SERVER_SIDE]: !!response['sessionRecording'],\n [CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE]: response.sessionRecording?.consoleLogRecordingEnabled,\n [SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE]: response.sessionRecording?.recorderVersion,\n [SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE]: response.sessionRecording?.networkPayloadCapture,\n })\n }\n\n const receivedSampleRate = response.sessionRecording?.sampleRate\n this._sampleRate =\n _isUndefined(receivedSampleRate) || _isNull(receivedSampleRate) ? null : parseFloat(receivedSampleRate)\n\n const receivedMinimumDuration = response.sessionRecording?.minimumDurationMilliseconds\n this._minimumDuration = _isUndefined(receivedMinimumDuration) ? null : receivedMinimumDuration\n\n this._linkedFlag = response.sessionRecording?.linkedFlag || null\n\n if (response.sessionRecording?.endpoint) {\n this._endpoint = response.sessionRecording?.endpoint\n }\n\n if (_isNumber(this._sampleRate)) {\n this.sessionManager.onSessionId((sessionId) => {\n this.makeSamplingDecision(sessionId)\n })\n }\n\n if (_isString(this._linkedFlag)) {\n const linkedFlag = this._linkedFlag\n this.instance.onFeatureFlags((flags) => {\n this._linkedFlagSeen = flags.includes(linkedFlag)\n })\n }\n\n this.receivedDecide = true\n this.startRecordingIfEnabled()\n }\n\n log(message: string, level: 'log' | 'warn' | 'error' = 'log') {\n this.instance.sessionRecording?.onRRwebEmit({\n type: 6,\n data: {\n plugin: 'rrweb/console@1',\n payload: {\n level,\n trace: [],\n // Even though it is a string we stringify it as that's what rrweb expects\n payload: [JSON.stringify(message)],\n },\n },\n timestamp: _timestamp(),\n })\n }\n\n private startCaptureAndTrySendingQueuedSnapshots() {\n this._startCapture()\n }\n\n private _startCapture() {\n if (_isUndefined(Object.assign)) {\n // According to the rrweb docs, rrweb is not supported on IE11 and below:\n // \"rrweb does not support IE11 and below because it uses the MutationObserver API which was supported by these browsers.\"\n // https://github.com/rrweb-io/rrweb/blob/master/guide.md#compatibility-note\n //\n // However, MutationObserver does exist on IE11, it just doesn't work well and does not detect all changes.\n // Instead, when we load \"recorder.js\", the first JS error is about \"Object.assign\" being undefined.\n // Thus instead of MutationObserver, we look for this function and block recording if it's undefined.\n return\n }\n\n // We do not switch recorder versions midway through a recording.\n if (this._captureStarted || this.instance.config.disable_session_recording) {\n return\n }\n\n this._captureStarted = true\n // We want to ensure the sessionManager is reset if necessary on load of the recorder\n this.sessionManager.checkAndGetSessionAndWindowId()\n\n const recorderJS = this.recordingVersion === 'v2' ? 'recorder-v2.js' : 'recorder.js'\n\n // If recorder.js is already loaded (if array.full.js snippet is used or posthog-js/dist/recorder is\n // imported) or matches the requested recorder version, don't load script. Otherwise, remotely import\n // recorder.js from cdn since it hasn't been loaded.\n if (this.instance.__loaded_recorder_version !== this.recordingVersion) {\n loadScript(this.instance.config.api_host + `/static/${recorderJS}?v=${Config.LIB_VERSION}`, (err) => {\n if (err) {\n return logger.error(`Could not load ${recorderJS}`, err)\n }\n\n this._onScriptLoaded()\n })\n } else {\n this._onScriptLoaded()\n }\n }\n\n private _isInteractiveEvent(event: eventWithTime) {\n return event.type === INCREMENTAL_SNAPSHOT_EVENT_TYPE && ACTIVE_SOURCES.indexOf(event.data?.source) !== -1\n }\n\n private _updateWindowAndSessionIds(event: eventWithTime) {\n // Some recording events are triggered by non-user events (e.g. \"X minutes ago\" text updating on the screen).\n // We don't want to extend the session or trigger a new session in these cases. These events are designated by event\n // type -> incremental update, and source -> mutation.\n\n const isUserInteraction = this._isInteractiveEvent(event)\n\n if (!isUserInteraction && !this.isIdle) {\n // We check if the lastActivityTimestamp is old enough to go idle\n if (event.timestamp - this._lastActivityTimestamp > RECORDING_IDLE_ACTIVITY_TIMEOUT_MS) {\n this.isIdle = true\n }\n }\n\n if (isUserInteraction) {\n this._lastActivityTimestamp = event.timestamp\n if (this.isIdle) {\n // Remove the idle state if set and trigger a full snapshot as we will have ignored previous mutations\n this.isIdle = false\n this._tryTakeFullSnapshot()\n }\n }\n\n if (this.isIdle) {\n return\n }\n\n // We only want to extend the session if it is an interactive event.\n const { windowId, sessionId } = this.sessionManager.checkAndGetSessionAndWindowId(\n !isUserInteraction,\n event.timestamp\n )\n\n const sessionIdChanged = this.sessionId !== sessionId\n const windowIdChanged = this.windowId !== windowId\n\n if (\n [FULL_SNAPSHOT_EVENT_TYPE, META_EVENT_TYPE].indexOf(event.type) === -1 &&\n (windowIdChanged || sessionIdChanged)\n ) {\n this._tryTakeFullSnapshot()\n }\n\n this.windowId = windowId\n this.sessionId = sessionId\n }\n\n private _tryTakeFullSnapshot(): boolean {\n // TODO this should ignore based on emit?\n if (!this._captureStarted) {\n return false\n }\n try {\n this.rrwebRecord?.takeFullSnapshot()\n return true\n } catch (e) {\n // Sometimes a race can occur where the recorder is not fully started yet, so we can't take a full snapshot.\n logger.error('Error taking full snapshot.', e)\n return false\n }\n }\n\n private _onScriptLoaded() {\n // rrweb config info: https://github.com/rrweb-io/rrweb/blob/7d5d0033258d6c29599fb08412202d9a2c7b9413/src/record/index.ts#L28\n const sessionRecordingOptions: recordOptions<eventWithTime> = {\n // select set of rrweb config options we expose to our users\n // see https://github.com/rrweb-io/rrweb/blob/master/guide.md\n blockClass: 'ph-no-capture',\n blockSelector: undefined,\n ignoreClass: 'ph-ignore-input',\n maskTextClass: 'ph-mask',\n maskTextSelector: undefined,\n maskTextFn: undefined,\n maskAllInputs: true,\n maskInputOptions: {},\n maskInputFn: undefined,\n slimDOMOptions: {},\n collectFonts: false,\n inlineStylesheet: true,\n recordCrossOriginIframes: false,\n }\n // We switched from loading all of rrweb to just the record part, but\n // keep backwards compatibility if someone hasn't upgraded PostHog\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.rrwebRecord = window.rrweb ? window.rrweb.record : window.rrwebRecord\n\n // only allows user to set our allow-listed options\n const userSessionRecordingOptions = this.instance.config.session_recording\n for (const [key, value] of Object.entries(userSessionRecordingOptions || {})) {\n if (key in sessionRecordingOptions) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n sessionRecordingOptions[key] = value\n }\n }\n\n if (!this.rrwebRecord) {\n logger.error(\n 'onScriptLoaded was called but rrwebRecord is not available. This indicates something has gone wrong.'\n )\n return\n }\n\n this.mutationRateLimiter =\n this.mutationRateLimiter ??\n new MutationRateLimiter(this.rrwebRecord, {\n onBlockedNode: (id, node) => {\n const message = `Too many mutations on node '${id}'. Rate limiting. This could be due to SVG animations or something similar`\n logger.info(message, {\n node: node,\n })\n\n this.log('[PostHog Recorder] ' + message, 'warn')\n },\n })\n\n const plugins = []\n\n if (assignableWindow.rrwebConsoleRecord && this.isConsoleLogCaptureEnabled) {\n plugins.push(assignableWindow.rrwebConsoleRecord.getRecordConsolePlugin())\n }\n if (this.networkPayloadCapture && _isFunction(assignableWindow.getRecordNetworkPlugin)) {\n plugins.push(\n assignableWindow.getRecordNetworkPlugin(\n buildNetworkRequestOptions(this.instance.config, this.networkPayloadCapture)\n )\n )\n }\n\n this.stopRrweb = this.rrwebRecord({\n emit: (event) => {\n this.onRRwebEmit(event)\n },\n plugins,\n ...sessionRecordingOptions,\n })\n\n // :TRICKY: rrweb does not capture navigation within SPA-s, so hook into our $pageview events to get access to all events.\n // Dropping the initial event is fine (it's always captured by rrweb).\n this.instance._addCaptureHook((eventName) => {\n // If anything could go wrong here it has the potential to block the main loop,\n // so we catch all errors.\n try {\n if (eventName === '$pageview') {\n const href = window ? this._maskUrl(window.location.href) : ''\n if (!href) {\n return\n }\n this.rrwebRecord?.addCustomEvent('$pageview', { href })\n }\n } catch (e) {\n logger.error('Could not add $pageview to rrweb session', e)\n }\n })\n\n // We reset the last activity timestamp, resetting the idle timer\n this._lastActivityTimestamp = Date.now()\n this.isIdle = false\n }\n\n onRRwebEmit(rawEvent: eventWithTime) {\n if (!rawEvent || !_isObject(rawEvent)) {\n return\n }\n\n if (rawEvent.type === EventType.Meta) {\n const href = this._maskUrl(rawEvent.data.href)\n if (!href) {\n return\n }\n rawEvent.data.href = href\n }\n\n const throttledEvent = this.mutationRateLimiter\n ? this.mutationRateLimiter.throttleMutations(rawEvent)\n : rawEvent\n\n if (!throttledEvent) {\n return\n }\n\n // TODO: Re-add ensureMaxMessageSize once we are confident in it\n const event = truncateLargeConsoleLogs(throttledEvent)\n const size = JSON.stringify(event).length\n\n this._updateWindowAndSessionIds(event)\n\n if (this.isIdle) {\n // When in an idle state we keep recording, but don't capture the events\n return\n }\n\n const properties = {\n $snapshot_bytes: size,\n $snapshot_data: event,\n $session_id: this.sessionId,\n $window_id: this.windowId,\n }\n\n if (this.status !== 'disabled') {\n this._captureSnapshotBuffered(properties)\n } else {\n this.clearBuffer()\n }\n }\n\n private _maskUrl(url: string): string | undefined {\n const userSessionRecordingOptions = this.instance.config.session_recording\n\n if (userSessionRecordingOptions.maskNetworkRequestFn) {\n let networkRequest: NetworkRequest | null | undefined = {\n url,\n }\n\n // TODO we should deprecate this and use the same function for this masking and the rrweb/network plugin\n // TODO or deprecate this and provide a new clearer name so this would be `maskURLPerformanceFn` or similar\n networkRequest = userSessionRecordingOptions.maskNetworkRequestFn(networkRequest)\n\n return networkRequest?.url\n }\n\n return url\n }\n\n private clearBuffer(): SnapshotBuffer {\n this.buffer = undefined\n\n return {\n size: 0,\n data: [],\n sessionId: this.sessionId,\n windowId: this.windowId,\n }\n }\n\n // the intention is a buffer that (currently) is used only after a decide response enables session recording\n // it is called ever X seconds using the flushBufferTimer so that we don't have to wait for the buffer to fill up\n // when it is called on a timer it assumes that it can definitely flush\n // it is flushed when the session id changes or the size of the buffered data gets too great (1mb by default)\n // first change: if the recording is in buffering mode,\n // flush buffer simply resets the timer and returns the existing flush buffer\n private _flushBuffer() {\n if (this.flushBufferTimer) {\n clearTimeout(this.flushBufferTimer)\n this.flushBufferTimer = undefined\n }\n\n const minimumDuration = this._minimumDuration\n const sessionDuration = this.sessionDuration\n // if we have old data in the buffer but the session has rotated then the\n // session duration might be negative, in that case we want to flush the buffer\n const isPositiveSessionDuration = _isNumber(sessionDuration) && sessionDuration >= 0\n const isBelowMinimumDuration =\n _isNumber(minimumDuration) && isPositiveSessionDuration && sessionDuration < minimumDuration\n\n if (this.status === 'buffering' || isBelowMinimumDuration) {\n this.flushBufferTimer = setTimeout(() => {\n this._flushBuffer()\n }, RECORDING_BUFFER_TIMEOUT)\n return this.buffer || this.clearBuffer()\n }\n\n if (this.buffer && this.buffer.data.length !== 0) {\n this._captureSnapshot({\n $snapshot_bytes: this.buffer.size,\n $snapshot_data: this.buffer.data,\n $session_id: this.buffer.sessionId,\n $window_id: this.buffer.windowId,\n })\n\n return this.clearBuffer()\n } else {\n return this.buffer || this.clearBuffer()\n }\n }\n\n private _captureSnapshotBuffered(properties: Properties) {\n const additionalBytes = 2 + (this.buffer?.data.length || 0) // 2 bytes for the array brackets and 1 byte for each comma\n if (\n !this.buffer ||\n this.buffer.size + properties.$snapshot_bytes + additionalBytes > RECORDING_MAX_EVENT_SIZE ||\n (!!this.buffer.sessionId && this.buffer.sessionId !== this.sessionId)\n ) {\n this.buffer = this._flushBuffer()\n }\n\n if (_isNull(this.buffer.sessionId) && !_isNull(this.sessionId)) {\n // session id starts null but has now been assigned, update the buffer\n this.buffer.sessionId = this.sessionId\n this.buffer.windowId = this.windowId\n }\n\n this.buffer.size += properties.$snapshot_bytes\n this.buffer.data.push(properties.$snapshot_data)\n\n if (!this.flushBufferTimer) {\n this.flushBufferTimer = setTimeout(() => {\n this._flushBuffer()\n }, RECORDING_BUFFER_TIMEOUT)\n }\n }\n\n private _captureSnapshot(properties: Properties) {\n // :TRICKY: Make sure we batch these requests, use a custom endpoint and don't truncate the strings.\n this.instance.capture('$snapshot', properties, {\n transport: 'XHR',\n method: 'POST',\n endpoint: this._endpoint,\n _noTruncate: true,\n _batchKey: SESSION_RECORDING_BATCH_KEY,\n _metrics: {\n rrweb_full_snapshot: properties.$snapshot_data.type === FULL_SNAPSHOT_EVENT_TYPE,\n },\n })\n }\n}\n"]}
@@ -12,6 +12,7 @@ var __values = (this && this.__values) || function(o) {
12
12
  import { isLocalhost } from '../../utils/request-utils';
13
13
  import { _isUndefined } from '../../utils/type-utils';
14
14
  import { logger } from '../../utils/logger';
15
+ import { window } from '../../utils/globals';
15
16
  var PERFORMANCE_EVENTS_MAPPING = {
16
17
  // BASE_PERFORMANCE_EVENT_COLUMNS
17
18
  entryType: 0,
@@ -1 +1 @@
1
- {"version":3,"file":"web-performance.js","sourceRoot":"","sources":["../../../../src/extensions/replay/web-performance.ts"],"names":[],"mappings":";;;;;;;;;;;AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAA;AAEvD,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAA;AACrD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAE3C,IAAM,0BAA0B,GAA8B;IAC1D,iCAAiC;IACjC,SAAS,EAAE,CAAC;IACZ,UAAU,EAAE,CAAC;IACb,IAAI,EAAE,CAAC;IAEP,yBAAyB;IACzB,SAAS,EAAE,CAAC;IACZ,aAAa,EAAE,CAAC;IAChB,WAAW,EAAE,CAAC;IACd,WAAW,EAAE,CAAC;IACd,UAAU,EAAE,CAAC;IACb,iBAAiB,EAAE,CAAC;IACpB,eAAe,EAAE,CAAC;IAClB,YAAY,EAAE,EAAE;IAChB,qBAAqB,EAAE,EAAE;IACzB,UAAU,EAAE,EAAE;IACd,YAAY,EAAE,EAAE;IAChB,aAAa,EAAE,EAAE;IACjB,WAAW,EAAE,EAAE;IACf,eAAe,EAAE,EAAE;IACnB,eAAe,EAAE,EAAE;IACnB,aAAa,EAAE,EAAE;IACjB,eAAe,EAAE,EAAE;IACnB,oBAAoB,EAAE,EAAE;IACxB,cAAc,EAAE,EAAE;IAClB,YAAY,E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CAAC,QAAQ;wBACzD,+CAA+C;wBAC/C,8EAA8E;wBAC9E,mEAAmE;wBACnE,4DAA4D;wBAC5D,8DAA8D;wBAC9D,GAAC,0BAA0B,CAAC,WAAW,CAAC,IAAG,cAAc;4BAC3D,CAAA;iBACL;;;;;;;;;SACJ;IACL,CAAC;IAED;;OAEG;IACK,wDAAuB,GAA/B,UAAgC,UAAkC;;QAC9D,IAAM,SAAS,GAAG,UAAU,CAAC,0BAA0B,CAAC,WAAW,CAAC,CAAC,CAAA;QAErE,MAAA,IAAI,CAAC,QAAQ,CAAC,gBAAgB,0CAAE,WAAW,CAAC;YACxC,IAAI,EAAE,CAAC;YACP,IAAI,EAAE;gBACF,MAAM,EAAE,mBAAmB;gBAC3B,OAAO,EAAE,UAAU;aACtB;YACD,SAAS,WAAA;SACZ,CAAC,CAAA;QAEF,4DAA4D;QAC5D,wBAAwB;QACxB,sBAAsB;QACtB,gDAAgD;QAChD,yBAAyB;QACzB,qCAAqC;QACrC,KAAK;IACT,CAAC;IACL,6BAAC;AAAD,CAAC,AAzKD,IAyKC;;AAED;;;;GAIG;AACH,IAAM,mBAAmB,GAAG,UAAC,KAAuB;IAChD,OAAA,KAAK,CAAC,SAAS,KAAK,YAAY,IAAI,KAAK,CAAC,SAAS,KAAK,UAAU;AAAlE,CAAkE,CAAA","sourcesContent":["import { PostHog } from '../../posthog-core'\nimport { DecideResponse, NetworkRequest } from '../../types'\nimport { isLocalhost } from '../../utils/request-utils'\n\nimport { _isUndefined } from '../../utils/type-utils'\nimport { logger } from '../../utils/logger'\n\nconst PERFORMANCE_EVENTS_MAPPING: { [key: string]: number } = {\n // BASE_PERFORMANCE_EVENT_COLUMNS\n entryType: 0,\n timeOrigin: 1,\n name: 2,\n\n // RESOURCE_EVENT_COLUMNS\n startTime: 3,\n redirectStart: 4,\n redirectEnd: 5,\n workerStart: 6,\n fetchStart: 7,\n domainLookupStart: 8,\n domainLookupEnd: 9,\n connectStart: 10,\n secureConnectionStart: 11,\n connectEnd: 12,\n requestStart: 13,\n responseStart: 14,\n responseEnd: 15,\n decodedBodySize: 16,\n encodedBodySize: 17,\n initiatorType: 18,\n nextHopProtocol: 19,\n renderBlockingStatus: 20,\n responseStatus: 21,\n transferSize: 22,\n\n // LARGEST_CONTENTFUL_PAINT_EVENT_COLUMNS\n element: 23,\n renderTime: 24,\n loadTime: 25,\n size: 26,\n id: 27,\n url: 28,\n\n // NAVIGATION_EVENT_COLUMNS\n domComplete: 29,\n domContentLoadedEvent: 30,\n domInteractive: 31,\n loadEventEnd: 32,\n loadEventStart: 33,\n redirectCount: 34,\n navigationType: 35,\n unloadEventEnd: 36,\n unloadEventStart: 37,\n\n // Added after v1\n duration: 39,\n timestamp: 40,\n\n // NOTE: CURRENTLY UNSUPPORTED\n // EVENT_TIMING_EVENT_COLUMNS\n // processingStart: null,\n // processingEnd: null,\n\n // MARK_AND_MEASURE_EVENT_COLUMNS\n // detail: null,\n}\n\nconst ENTRY_TYPES_TO_OBSERVE = [\n // 'event', // This is too noisy as it covers all browser events\n 'first-input',\n // 'mark', // Mark is used too liberally. We would need to filter for specific marks\n // 'measure', // Measure is used too liberally. We would need to filter for specific measures\n 'navigation',\n 'paint',\n 'resource',\n]\n\nconst PERFORMANCE_INGESTION_ENDPOINT = '/e/'\n// Don't monitor posthog paths because then events cause performance events which are events and the snake eats its tail 😱\nconst POSTHOG_PATHS_TO_IGNORE = ['/s/', PERFORMANCE_INGESTION_ENDPOINT]\n\nexport class WebPerformanceObserver {\n instance: PostHog\n remoteEnabled: boolean | undefined\n observer: PerformanceObserver | undefined\n\n // Util to help developers working on this feature manually override\n _forceAllowLocalhost = false\n\n constructor(instance: PostHog) {\n this.instance = instance\n }\n\n startObservingIfEnabled() {\n if (this.isEnabled()) {\n this.startObserving()\n } else {\n this.stopObserving()\n }\n }\n\n startObserving() {\n if (this.observer) {\n return\n }\n\n if (_isUndefined(window?.PerformanceObserver?.supportedEntryTypes)) {\n logger.info(\n '[PerformanceObserver] not started because PerformanceObserver is not supported by this browser.'\n )\n return\n }\n\n if (isLocalhost() && !this._forceAllowLocalhost) {\n logger.info('[PerformanceObserver] not started because we are on localhost.')\n return\n }\n\n try {\n // compat checked above with early return\n // eslint-disable-next-line compat/compat\n this.observer = new PerformanceObserver((list) => {\n list.getEntries().forEach((entry) => {\n this._capturePerformanceEvent(entry)\n })\n })\n\n // compat checked above with early return\n // eslint-disable-next-line compat/compat\n const entryTypes = PerformanceObserver.supportedEntryTypes.filter((x) => ENTRY_TYPES_TO_OBSERVE.includes(x))\n\n entryTypes.forEach((entryType) => {\n this.observer?.observe({ type: entryType, buffered: true })\n })\n } catch (e) {\n logger.error('PostHog failed to start performance observer', e)\n this.stopObserving()\n }\n }\n\n stopObserving() {\n if (this.observer) {\n this.observer.disconnect()\n this.observer = undefined\n }\n }\n\n isObserving() {\n return !!this.observer\n }\n\n isEnabled() {\n return this.instance.config.capture_performance ?? this.remoteEnabled ?? false\n }\n\n afterDecideResponse(response: DecideResponse) {\n this.remoteEnabled = response.capturePerformance || false\n if (this.isEnabled()) {\n this.startObserving()\n }\n }\n\n _capturePerformanceEvent(event: PerformanceEntry) {\n // NOTE: We don't want to capture our own request events.\n\n if (event.name.indexOf(this.instance.config.api_host) === 0) {\n const path = event.name.replace(this.instance.config.api_host, '')\n\n if (POSTHOG_PATHS_TO_IGNORE.find((x) => path.indexOf(x) === 0)) {\n return\n }\n }\n\n // NOTE: This is minimal atm but will include more options when we move to the\n // built-in rrweb network recorder\n let networkRequest: NetworkRequest | null | undefined = {\n url: event.name,\n }\n\n const userSessionRecordingOptions = this.instance.config.session_recording\n\n if (userSessionRecordingOptions.maskNetworkRequestFn) {\n networkRequest = userSessionRecordingOptions.maskNetworkRequestFn(networkRequest)\n }\n\n if (!networkRequest) {\n return\n }\n\n const eventJson = event.toJSON()\n eventJson.name = networkRequest.url\n const properties: { [key: number]: any } = {}\n // kudos to sentry javascript sdk for excellent background on why to use Date.now() here\n // https://github.com/getsentry/sentry-javascript/blob/e856e40b6e71a73252e788cd42b5260f81c9c88e/packages/utils/src/time.ts#L70\n // can't start observer if performance.now() is not available\n // eslint-disable-next-line compat/compat\n const timeOrigin = Math.floor(Date.now() - performance.now())\n properties[PERFORMANCE_EVENTS_MAPPING['timeOrigin']] = timeOrigin\n // clickhouse can't ingest timestamps that are floats\n // (in this case representing fractions of a millisecond we don't care about anyway)\n properties[PERFORMANCE_EVENTS_MAPPING['timestamp']] = Math.floor(timeOrigin + event.startTime)\n for (const key in PERFORMANCE_EVENTS_MAPPING) {\n if (!_isUndefined(eventJson[key])) {\n properties[PERFORMANCE_EVENTS_MAPPING[key]] = eventJson[key]\n }\n }\n\n this.capturePerformanceEvent(properties)\n\n if (exposesServerTiming(event)) {\n for (const timing of event.serverTiming || []) {\n this.capturePerformanceEvent({\n [PERFORMANCE_EVENTS_MAPPING['timeOrigin']]: timeOrigin,\n [PERFORMANCE_EVENTS_MAPPING['timestamp']]: Math.floor(timeOrigin + event.startTime),\n [PERFORMANCE_EVENTS_MAPPING['name']]: timing.name,\n [PERFORMANCE_EVENTS_MAPPING['duration']]: timing.duration,\n // the spec has a closed list of possible types\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType\n // but, we need to know this was a server timing so that we know to\n // match it to the appropriate navigation or resource timing\n // that matching will have to be on timestamp and $current_url\n [PERFORMANCE_EVENTS_MAPPING['entryType']]: 'serverTiming',\n })\n }\n }\n }\n\n /**\n * :TRICKY: Make sure we batch these requests, and don't truncate the strings.\n */\n private capturePerformanceEvent(properties: { [key: number]: any }) {\n const timestamp = properties[PERFORMANCE_EVENTS_MAPPING['timestamp']]\n\n this.instance.sessionRecording?.onRRwebEmit({\n type: 6, // EventType.Plugin,\n data: {\n plugin: 'posthog/network@1',\n payload: properties,\n },\n timestamp,\n })\n\n // this.instance.capture('$performance_event', properties, {\n // transport: 'XHR',\n // method: 'POST',\n // endpoint: PERFORMANCE_INGESTION_ENDPOINT,\n // _noTruncate: true,\n // _batchKey: 'performanceEvent',\n // })\n }\n}\n\n/**\n * Check if this PerformanceEntry is either a PerformanceResourceTiming or a PerformanceNavigationTiming\n * NB PerformanceNavigationTiming extends PerformanceResourceTiming\n * Here we don't care which interface it implements as both expose `serverTimings`\n */\nconst exposesServerTiming = (event: PerformanceEntry): event is PerformanceResourceTiming =>\n event.entryType === 'navigation' || event.entryType === 'resource'\n"]}
1
+ {"version":3,"file":"web-performance.js","sourceRoot":"","sources":["../../../../src/extensions/replay/web-performance.ts"],"names":[],"mappings":";;;;;;;;;;;AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAA;AAEvD,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAA;AACrD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AAE5C,IAAM,0BAA0B,GAA8B;IAC1D,iCAAiC;IACjC,SAAS,EAAE,CAAC;IACZ,UAAU,EAAE,CAAC;IACb,IAAI,EAAE,CAAC;IAEP,yBAAyB;IACzB,SAAS,EAAE,CAAC;IACZ,aAAa,EAAE,CAAC;IAChB,WAAW,EAAE,CAAC;IACd,WAAW,EAAE,CAAC;IACd,UAAU,EAAE,CAAC;IACb,iBAAiB,EAAE,CAAC;IACpB,eAAe,EAAE,CAAC;IAClB,YAAY,EAAE,EAAE;IAChB,qBAAqB,EAAE,EAAE;IACzB,UAAU,EAAE,EAAE;IACd,YAAY,EAAE,EAAE;IAChB,aAAa,EAAE,EAAE;IACjB,WAAW,EAAE,EAAE;IACf,eAAe,EAAE,EAAE;IACnB,eAAe,EAAE,EAAE;IACnB,aAAa,EAAE,EAAE;IACjB,eAAe,EAAE,EAAE;IACnB,oBAAoB,EAAE,EAAE;IACxB,cAAc,EAAE,EAAE;IAClB,YAAY,EAAE,EAAE;IAEhB,yCAAyC;IACzC,OAAO,EAAE,EAAE;IACX,UAAU,EAAE,EAAE;IACd,QAAQ,EAAE,EAAE;I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C9D,GAAC,0BAA0B,CAAC,WAAW,CAAC,IAAG,cAAc;4BAC3D,CAAA;iBACL;;;;;;;;;SACJ;IACL,CAAC;IAED;;OAEG;IACK,wDAAuB,GAA/B,UAAgC,UAAkC;;QAC9D,IAAM,SAAS,GAAG,UAAU,CAAC,0BAA0B,CAAC,WAAW,CAAC,CAAC,CAAA;QAErE,MAAA,IAAI,CAAC,QAAQ,CAAC,gBAAgB,0CAAE,WAAW,CAAC;YACxC,IAAI,EAAE,CAAC;YACP,IAAI,EAAE;gBACF,MAAM,EAAE,mBAAmB;gBAC3B,OAAO,EAAE,UAAU;aACtB;YACD,SAAS,WAAA;SACZ,CAAC,CAAA;QAEF,4DAA4D;QAC5D,wBAAwB;QACxB,sBAAsB;QACtB,gDAAgD;QAChD,yBAAyB;QACzB,qCAAqC;QACrC,KAAK;IACT,CAAC;IACL,6BAAC;AAAD,CAAC,AAzKD,IAyKC;;AAED;;;;GAIG;AACH,IAAM,mBAAmB,GAAG,UAAC,KAAuB;IAChD,OAAA,KAAK,CAAC,SAAS,KAAK,YAAY,IAAI,KAAK,CAAC,SAAS,KAAK,UAAU;AAAlE,CAAkE,CAAA","sourcesContent":["import { PostHog } from '../../posthog-core'\nimport { DecideResponse, NetworkRequest } from '../../types'\nimport { isLocalhost } from '../../utils/request-utils'\n\nimport { _isUndefined } from '../../utils/type-utils'\nimport { logger } from '../../utils/logger'\nimport { window } from '../../utils/globals'\n\nconst PERFORMANCE_EVENTS_MAPPING: { [key: string]: number } = {\n // BASE_PERFORMANCE_EVENT_COLUMNS\n entryType: 0,\n timeOrigin: 1,\n name: 2,\n\n // RESOURCE_EVENT_COLUMNS\n startTime: 3,\n redirectStart: 4,\n redirectEnd: 5,\n workerStart: 6,\n fetchStart: 7,\n domainLookupStart: 8,\n domainLookupEnd: 9,\n connectStart: 10,\n secureConnectionStart: 11,\n connectEnd: 12,\n requestStart: 13,\n responseStart: 14,\n responseEnd: 15,\n decodedBodySize: 16,\n encodedBodySize: 17,\n initiatorType: 18,\n nextHopProtocol: 19,\n renderBlockingStatus: 20,\n responseStatus: 21,\n transferSize: 22,\n\n // LARGEST_CONTENTFUL_PAINT_EVENT_COLUMNS\n element: 23,\n renderTime: 24,\n loadTime: 25,\n size: 26,\n id: 27,\n url: 28,\n\n // NAVIGATION_EVENT_COLUMNS\n domComplete: 29,\n domContentLoadedEvent: 30,\n domInteractive: 31,\n loadEventEnd: 32,\n loadEventStart: 33,\n redirectCount: 34,\n navigationType: 35,\n unloadEventEnd: 36,\n unloadEventStart: 37,\n\n // Added after v1\n duration: 39,\n timestamp: 40,\n\n // NOTE: CURRENTLY UNSUPPORTED\n // EVENT_TIMING_EVENT_COLUMNS\n // processingStart: null,\n // processingEnd: null,\n\n // MARK_AND_MEASURE_EVENT_COLUMNS\n // detail: null,\n}\n\nconst ENTRY_TYPES_TO_OBSERVE = [\n // 'event', // This is too noisy as it covers all browser events\n 'first-input',\n // 'mark', // Mark is used too liberally. We would need to filter for specific marks\n // 'measure', // Measure is used too liberally. We would need to filter for specific measures\n 'navigation',\n 'paint',\n 'resource',\n]\n\nconst PERFORMANCE_INGESTION_ENDPOINT = '/e/'\n// Don't monitor posthog paths because then events cause performance events which are events and the snake eats its tail 😱\nconst POSTHOG_PATHS_TO_IGNORE = ['/s/', PERFORMANCE_INGESTION_ENDPOINT]\n\nexport class WebPerformanceObserver {\n instance: PostHog\n remoteEnabled: boolean | undefined\n observer: PerformanceObserver | undefined\n\n // Util to help developers working on this feature manually override\n _forceAllowLocalhost = false\n\n constructor(instance: PostHog) {\n this.instance = instance\n }\n\n startObservingIfEnabled() {\n if (this.isEnabled()) {\n this.startObserving()\n } else {\n this.stopObserving()\n }\n }\n\n startObserving() {\n if (this.observer) {\n return\n }\n\n if (_isUndefined(window?.PerformanceObserver?.supportedEntryTypes)) {\n logger.info(\n '[PerformanceObserver] not started because PerformanceObserver is not supported by this browser.'\n )\n return\n }\n\n if (isLocalhost() && !this._forceAllowLocalhost) {\n logger.info('[PerformanceObserver] not started because we are on localhost.')\n return\n }\n\n try {\n // compat checked above with early return\n // eslint-disable-next-line compat/compat\n this.observer = new PerformanceObserver((list) => {\n list.getEntries().forEach((entry) => {\n this._capturePerformanceEvent(entry)\n })\n })\n\n // compat checked above with early return\n // eslint-disable-next-line compat/compat\n const entryTypes = PerformanceObserver.supportedEntryTypes.filter((x) => ENTRY_TYPES_TO_OBSERVE.includes(x))\n\n entryTypes.forEach((entryType) => {\n this.observer?.observe({ type: entryType, buffered: true })\n })\n } catch (e) {\n logger.error('PostHog failed to start performance observer', e)\n this.stopObserving()\n }\n }\n\n stopObserving() {\n if (this.observer) {\n this.observer.disconnect()\n this.observer = undefined\n }\n }\n\n isObserving() {\n return !!this.observer\n }\n\n isEnabled() {\n return this.instance.config.capture_performance ?? this.remoteEnabled ?? false\n }\n\n afterDecideResponse(response: DecideResponse) {\n this.remoteEnabled = response.capturePerformance || false\n if (this.isEnabled()) {\n this.startObserving()\n }\n }\n\n _capturePerformanceEvent(event: PerformanceEntry) {\n // NOTE: We don't want to capture our own request events.\n\n if (event.name.indexOf(this.instance.config.api_host) === 0) {\n const path = event.name.replace(this.instance.config.api_host, '')\n\n if (POSTHOG_PATHS_TO_IGNORE.find((x) => path.indexOf(x) === 0)) {\n return\n }\n }\n\n // NOTE: This is minimal atm but will include more options when we move to the\n // built-in rrweb network recorder\n let networkRequest: NetworkRequest | null | undefined = {\n url: event.name,\n }\n\n const userSessionRecordingOptions = this.instance.config.session_recording\n\n if (userSessionRecordingOptions.maskNetworkRequestFn) {\n networkRequest = userSessionRecordingOptions.maskNetworkRequestFn(networkRequest)\n }\n\n if (!networkRequest) {\n return\n }\n\n const eventJson = event.toJSON()\n eventJson.name = networkRequest.url\n const properties: { [key: number]: any } = {}\n // kudos to sentry javascript sdk for excellent background on why to use Date.now() here\n // https://github.com/getsentry/sentry-javascript/blob/e856e40b6e71a73252e788cd42b5260f81c9c88e/packages/utils/src/time.ts#L70\n // can't start observer if performance.now() is not available\n // eslint-disable-next-line compat/compat\n const timeOrigin = Math.floor(Date.now() - performance.now())\n properties[PERFORMANCE_EVENTS_MAPPING['timeOrigin']] = timeOrigin\n // clickhouse can't ingest timestamps that are floats\n // (in this case representing fractions of a millisecond we don't care about anyway)\n properties[PERFORMANCE_EVENTS_MAPPING['timestamp']] = Math.floor(timeOrigin + event.startTime)\n for (const key in PERFORMANCE_EVENTS_MAPPING) {\n if (!_isUndefined(eventJson[key])) {\n properties[PERFORMANCE_EVENTS_MAPPING[key]] = eventJson[key]\n }\n }\n\n this.capturePerformanceEvent(properties)\n\n if (exposesServerTiming(event)) {\n for (const timing of event.serverTiming || []) {\n this.capturePerformanceEvent({\n [PERFORMANCE_EVENTS_MAPPING['timeOrigin']]: timeOrigin,\n [PERFORMANCE_EVENTS_MAPPING['timestamp']]: Math.floor(timeOrigin + event.startTime),\n [PERFORMANCE_EVENTS_MAPPING['name']]: timing.name,\n [PERFORMANCE_EVENTS_MAPPING['duration']]: timing.duration,\n // the spec has a closed list of possible types\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType\n // but, we need to know this was a server timing so that we know to\n // match it to the appropriate navigation or resource timing\n // that matching will have to be on timestamp and $current_url\n [PERFORMANCE_EVENTS_MAPPING['entryType']]: 'serverTiming',\n })\n }\n }\n }\n\n /**\n * :TRICKY: Make sure we batch these requests, and don't truncate the strings.\n */\n private capturePerformanceEvent(properties: { [key: number]: any }) {\n const timestamp = properties[PERFORMANCE_EVENTS_MAPPING['timestamp']]\n\n this.instance.sessionRecording?.onRRwebEmit({\n type: 6, // EventType.Plugin,\n data: {\n plugin: 'posthog/network@1',\n payload: properties,\n },\n timestamp,\n })\n\n // this.instance.capture('$performance_event', properties, {\n // transport: 'XHR',\n // method: 'POST',\n // endpoint: PERFORMANCE_INGESTION_ENDPOINT,\n // _noTruncate: true,\n // _batchKey: 'performanceEvent',\n // })\n }\n}\n\n/**\n * Check if this PerformanceEntry is either a PerformanceResourceTiming or a PerformanceNavigationTiming\n * NB PerformanceNavigationTiming extends PerformanceResourceTiming\n * Here we don't care which interface it implements as both expose `serverTimings`\n */\nconst exposesServerTiming = (event: PerformanceEntry): event is PerformanceResourceTiming =>\n event.entryType === 'navigation' || event.entryType === 'resource'\n"]}
@@ -46,6 +46,10 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
46
46
  return to.concat(ar || Array.prototype.slice.call(from));
47
47
  };
48
48
  import { _isUndefined } from '../utils/type-utils';
49
+ import { window as _window, document as _document } from '../utils/globals';
50
+ // We cast the types here which is dangerous but protected by the top level generateSurveys call
51
+ var window = _window;
52
+ var document = _document;
49
53
  var satisfiedEmoji = '<svg class="emoji-svg" xmlns="http://www.w3.org/2000/svg" height="48" viewBox="0 -960 960 960" width="48"><path d="M626-533q22.5 0 38.25-15.75T680-587q0-22.5-15.75-38.25T626-641q-22.5 0-38.25 15.75T572-587q0 22.5 15.75 38.25T626-533Zm-292 0q22.5 0 38.25-15.75T388-587q0-22.5-15.75-38.25T334-641q-22.5 0-38.25 15.75T280-587q0 22.5 15.75 38.25T334-533Zm146 272q66 0 121.5-35.5T682-393h-52q-23 40-63 61.5T480.5-310q-46.5 0-87-21T331-393h-53q26 61 81 96.5T480-261Zm0 181q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 340q142.375 0 241.188-98.812Q820-337.625 820-480t-98.812-241.188Q622.375-820 480-820t-241.188 98.812Q140-622.375 140-480t98.812 241.188Q337.625-140 480-140Z"/></svg>';
50
54
  var neutralEmoji = '<svg class="emoji-svg" xmlns="http://www.w3.org/2000/svg" height="48" viewBox="0 -960 960 960" width="48"><path d="M626-533q22.5 0 38.25-15.75T680-587q0-22.5-15.75-38.25T626-641q-22.5 0-38.25 15.75T572-587q0 22.5 15.75 38.25T626-533Zm-292 0q22.5 0 38.25-15.75T388-587q0-22.5-15.75-38.25T334-641q-22.5 0-38.25 15.75T280-587q0 22.5 15.75 38.25T334-533Zm20 194h253v-49H354v49ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 340q142.375 0 241.188-98.812Q820-337.625 820-480t-98.812-241.188Q622.375-820 480-820t-241.188 98.812Q140-622.375 140-480t98.812 241.188Q337.625-140 480-140Z"/></svg>';
51
55
  var dissatisfiedEmoji = '<svg class="emoji-svg" xmlns="http://www.w3.org/2000/svg" height="48" viewBox="0 -960 960 960" width="48"><path d="M626-533q22.5 0 38.25-15.75T680-587q0-22.5-15.75-38.25T626-641q-22.5 0-38.25 15.75T572-587q0 22.5 15.75 38.25T626-533Zm-292 0q22.5 0 38.25-15.75T388-587q0-22.5-15.75-38.25T334-641q-22.5 0-38.25 15.75T280-587q0 22.5 15.75 38.25T334-533Zm146.174 116Q413-417 358.5-379.5T278-280h53q22-42 62.173-65t87.5-23Q528-368 567.5-344.5T630-280h52q-25-63-79.826-100-54.826-37-122-37ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 340q142.375 0 241.188-98.812Q820-337.625 820-480t-98.812-241.188Q622.375-820 480-820t-241.188 98.812Q140-622.375 140-480t98.812 241.188Q337.625-140 480-140Z"/></svg>';
@@ -613,12 +617,16 @@ function showQuestion(n, surveyId) {
613
617
  function nextQuestion(currentQuestionIdx, surveyId) {
614
618
  var _a, _b;
615
619
  // figure out which tab to display
616
- var tabs = (_b = (_a = document
617
- .getElementsByClassName("PostHogSurvey".concat(surveyId))[0]) === null || _a === void 0 ? void 0 : _a.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelectorAll('.tab');
620
+ var tabs = (_b = (_a = document === null || document === void 0 ? void 0 : document.getElementsByClassName("PostHogSurvey".concat(surveyId))[0]) === null || _a === void 0 ? void 0 : _a.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelectorAll('.tab');
618
621
  tabs[currentQuestionIdx].style.display = 'none';
619
622
  showQuestion(currentQuestionIdx + 1, surveyId);
620
623
  }
624
+ // This is the main exported function
621
625
  export function generateSurveys(posthog) {
626
+ // NOTE: Important to ensure we never try and run surveys without a window environment
627
+ if (!document || !window) {
628
+ return;
629
+ }
622
630
  callSurveys(posthog, true);
623
631
  // recalculate surveys every 3 seconds to check if URL or selectors have changed
624
632
  setInterval(function () {