posthog-js 1.90.0 → 1.90.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.
package/lib/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "posthog-js",
3
- "version": "1.90.0",
3
+ "version": "1.90.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",
@@ -7,6 +7,7 @@ export declare const AUTOCAPTURE_DISABLED_SERVER_SIDE = "$autocapture_disabled_s
7
7
  export declare const SESSION_RECORDING_ENABLED_SERVER_SIDE = "$session_recording_enabled_server_side";
8
8
  export declare const CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = "$console_log_recording_enabled_server_side";
9
9
  export declare const SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE = "$session_recording_recorder_version_server_side";
10
+ export declare const SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE = "$session_recording_network_payload_capture";
10
11
  export declare const SESSION_ID = "$sesid";
11
12
  export declare const SESSION_RECORDING_IS_SAMPLED = "$session_is_sampled";
12
13
  export declare const ENABLED_FEATURE_FLAGS = "$enabled_feature_flags";
@@ -12,6 +12,7 @@ export var AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side
12
12
  export var SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side';
13
13
  export var CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = '$console_log_recording_enabled_server_side';
14
14
  export var SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE = '$session_recording_recorder_version_server_side'; // follows rrweb versioning
15
+ export var SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE = '$session_recording_network_payload_capture';
15
16
  export var SESSION_ID = '$sesid';
16
17
  export var SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled';
17
18
  export var ENABLED_FEATURE_FLAGS = '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BAA+B,GAAG;IAC3C,sBAAsB;IACtB,YAAY;IACZ,gBAAgB;IAChB,gBAAgB;IAChB,qCAAqC;IACrC,UAAU;IACV,qBAAqB;IACrB,UAAU;IACV,qBAAqB;IACrB,iCAAiC;IACjC,2BAA2B;IAC3B,4BAA4B;IAC5B,OAAO;IACP,kBAAkB;IAClB,oBAAoB;CACvB,CAAA","sourcesContent":["/*\n * Constants\n */\n\n/* PROPERTY KEYS */\n\n// This key is deprecated, but we want to check for it to see whether aliasing is allowed.\nexport const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id'\nexport const DISTINCT_ID = 'distinct_id'\nexport const ALIAS_ID_KEY = '__alias'\nexport const CAMPAIGN_IDS_KEY = '__cmpns'\nexport const EVENT_TIMERS_KEY = '__timers'\nexport const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side'\nexport const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side'\nexport const CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = '$console_log_recording_enabled_server_side'\nexport const SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE = '$session_recording_recorder_version_server_side' // follows rrweb versioning\nexport const SESSION_ID = '$sesid'\nexport const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled'\nexport const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags'\nexport const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features'\nexport const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties'\nexport const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties'\nexport const SURVEYS = '$surveys'\nexport const FLAG_CALL_REPORTED = '$flag_call_reported'\nexport const USER_STATE = '$user_state'\nexport const POSTHOG_QUOTA_LIMITED = '$posthog_quota_limited'\nexport const CLIENT_SESSION_PROPS = '$client_session_props'\n\n// These are properties that are reserved and will not be automatically included in events\nexport const PERSISTENCE_RESERVED_PROPERTIES = [\n PEOPLE_DISTINCT_ID_KEY,\n ALIAS_ID_KEY,\n CAMPAIGN_IDS_KEY,\n EVENT_TIMERS_KEY,\n SESSION_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_ID,\n ENABLED_FEATURE_FLAGS,\n USER_STATE,\n POSTHOG_QUOTA_LIMITED,\n PERSISTENCE_EARLY_ACCESS_FEATURES,\n STORED_GROUP_PROPERTIES_KEY,\n STORED_PERSON_PROPERTIES_KEY,\n SURVEYS,\n FLAG_CALL_REPORTED,\n CLIENT_SESSION_PROPS,\n]\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,mBAAmB;AAEnB,0FAA0F;AAC1F,MAAM,CAAC,IAAM,sBAAsB,GAAG,qBAAqB,CAAA;AAC3D,MAAM,CAAC,IAAM,WAAW,GAAG,aAAa,CAAA;AACxC,MAAM,CAAC,IAAM,YAAY,GAAG,SAAS,CAAA;AACrC,MAAM,CAAC,IAAM,gBAAgB,GAAG,SAAS,CAAA;AACzC,MAAM,CAAC,IAAM,gBAAgB,GAAG,UAAU,CAAA;AAC1C,MAAM,CAAC,IAAM,gCAAgC,GAAG,mCAAmC,CAAA;AACnF,MAAM,CAAC,IAAM,qCAAqC,GAAG,wCAAwC,CAAA;AAC7F,MAAM,CAAC,IAAM,yCAAyC,GAAG,4CAA4C,CAAA;AACrG,MAAM,CAAC,IAAM,8CAA8C,GAAG,iDAAiD,CAAA,CAAC,2BAA2B;AAC3I,MAAM,CAAC,IAAM,yCAAyC,GAAG,4CAA4C,CAAA;AACrG,MAAM,CAAC,IAAM,UAAU,GAAG,QAAQ,CAAA;AAClC,MAAM,CAAC,IAAM,4BAA4B,GAAG,qBAAqB,CAAA;AACjE,MAAM,CAAC,IAAM,qBAAqB,GAAG,wBAAwB,CAAA;AAC7D,MAAM,CAAC,IAAM,iCAAiC,GAAG,wBAAwB,CAAA;AACzE,MAAM,CAAC,IAAM,4BAA4B,GAAG,2BAA2B,CAAA;AACvE,MAAM,CAAC,IAAM,2BAA2B,GAAG,0BAA0B,CAAA;AACrE,MAAM,CAAC,IAAM,OAAO,GAAG,UAAU,CAAA;AACjC,MAAM,CAAC,IAAM,kBAAkB,GAAG,qBAAqB,CAAA;AACvD,MAAM,CAAC,IAAM,UAAU,GAAG,aAAa,CAAA;AACvC,MAAM,CAAC,IAAM,qBAAqB,GAAG,wBAAwB,CAAA;AAC7D,MAAM,CAAC,IAAM,oBAAoB,GAAG,uBAAuB,CAAA;AAE3D,0FAA0F;AAC1F,MAAM,CAAC,IAAM,+BAA+B,GAAG;IAC3C,sBAAsB;IACtB,YAAY;IACZ,gBAAgB;IAChB,gBAAgB;IAChB,qCAAqC;IACrC,UAAU;IACV,qBAAqB;IACrB,UAAU;IACV,qBAAqB;IACrB,iCAAiC;IACjC,2BAA2B;IAC3B,4BAA4B;IAC5B,OAAO;IACP,kBAAkB;IAClB,oBAAoB;CACvB,CAAA","sourcesContent":["/*\n * Constants\n */\n\n/* PROPERTY KEYS */\n\n// This key is deprecated, but we want to check for it to see whether aliasing is allowed.\nexport const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id'\nexport const DISTINCT_ID = 'distinct_id'\nexport const ALIAS_ID_KEY = '__alias'\nexport const CAMPAIGN_IDS_KEY = '__cmpns'\nexport const EVENT_TIMERS_KEY = '__timers'\nexport const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side'\nexport const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side'\nexport const CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = '$console_log_recording_enabled_server_side'\nexport const SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE = '$session_recording_recorder_version_server_side' // follows rrweb versioning\nexport const SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE = '$session_recording_network_payload_capture'\nexport const SESSION_ID = '$sesid'\nexport const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled'\nexport const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags'\nexport const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features'\nexport const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties'\nexport const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties'\nexport const SURVEYS = '$surveys'\nexport const FLAG_CALL_REPORTED = '$flag_call_reported'\nexport const USER_STATE = '$user_state'\nexport const POSTHOG_QUOTA_LIMITED = '$posthog_quota_limited'\nexport const CLIENT_SESSION_PROPS = '$client_session_props'\n\n// These are properties that are reserved and will not be automatically included in events\nexport const PERSISTENCE_RESERVED_PROPERTIES = [\n PEOPLE_DISTINCT_ID_KEY,\n ALIAS_ID_KEY,\n CAMPAIGN_IDS_KEY,\n EVENT_TIMERS_KEY,\n SESSION_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_ID,\n ENABLED_FEATURE_FLAGS,\n USER_STATE,\n POSTHOG_QUOTA_LIMITED,\n PERSISTENCE_EARLY_ACCESS_FEATURES,\n STORED_GROUP_PROPERTIES_KEY,\n STORED_PERSON_PROPERTIES_KEY,\n SURVEYS,\n FLAG_CALL_REPORTED,\n CLIENT_SESSION_PROPS,\n]\n"]}
@@ -16,7 +16,6 @@ export declare class SessionRecording {
16
16
  private receivedDecide;
17
17
  private rrwebRecord;
18
18
  private isIdle;
19
- private _networkPayloadCapture;
20
19
  private _linkedFlagSeen;
21
20
  private _lastActivityTimestamp;
22
21
  private windowId;
@@ -31,6 +30,7 @@ export declare class SessionRecording {
31
30
  private get isRecordingEnabled();
32
31
  private get isConsoleLogCaptureEnabled();
33
32
  private get recordingVersion();
33
+ private get networkPayloadCapture();
34
34
  /**
35
35
  * defaults to buffering mode until a decide response is received
36
36
  * once a decide response is received status can be disabled, active or sampled
@@ -36,7 +36,7 @@ var __read = (this && this.__read) || function (o, n) {
36
36
  }
37
37
  return ar;
38
38
  };
39
- import { CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE, SESSION_RECORDING_ENABLED_SERVER_SIDE, SESSION_RECORDING_IS_SAMPLED, SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE, } from '../../constants';
39
+ import { CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE, SESSION_RECORDING_ENABLED_SERVER_SIDE, SESSION_RECORDING_IS_SAMPLED, SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE, SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE, } from '../../constants';
40
40
  import { FULL_SNAPSHOT_EVENT_TYPE, INCREMENTAL_SNAPSHOT_EVENT_TYPE, META_EVENT_TYPE, MutationRateLimiter, truncateLargeConsoleLogs, } from './sessionrecording-utils';
41
41
  import { EventType } from '@rrweb/types';
42
42
  import Config from '../../config';
@@ -87,7 +87,6 @@ var SessionRecording = /** @class */ (function () {
87
87
  function SessionRecording(instance) {
88
88
  var _this = this;
89
89
  this.isIdle = false;
90
- this._networkPayloadCapture = undefined;
91
90
  this._linkedFlagSeen = false;
92
91
  this._lastActivityTimestamp = Date.now();
93
92
  this.windowId = null;
@@ -178,6 +177,21 @@ var SessionRecording = /** @class */ (function () {
178
177
  enumerable: false,
179
178
  configurable: true
180
179
  });
180
+ Object.defineProperty(SessionRecording.prototype, "networkPayloadCapture", {
181
+ get: function () {
182
+ var _a, _b;
183
+ var networkPayloadCapture_server_side = this.instance.get_property(SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE);
184
+ var networkPayloadCapture_client_side = {
185
+ recordHeaders: (_a = this.instance.config.session_recording) === null || _a === void 0 ? void 0 : _a.recordHeaders,
186
+ recordBody: (_b = this.instance.config.session_recording) === null || _b === void 0 ? void 0 : _b.recordBody,
187
+ };
188
+ var headersEnabled = (networkPayloadCapture_client_side === null || networkPayloadCapture_client_side === void 0 ? void 0 : networkPayloadCapture_client_side.recordHeaders) || (networkPayloadCapture_server_side === null || networkPayloadCapture_server_side === void 0 ? void 0 : networkPayloadCapture_server_side.recordHeaders);
189
+ var bodyEnabled = (networkPayloadCapture_client_side === null || networkPayloadCapture_client_side === void 0 ? void 0 : networkPayloadCapture_client_side.recordBody) || (networkPayloadCapture_server_side === null || networkPayloadCapture_server_side === void 0 ? void 0 : networkPayloadCapture_server_side.recordBody);
190
+ return headersEnabled || bodyEnabled ? { recordHeaders: headersEnabled, recordBody: bodyEnabled } : undefined;
191
+ },
192
+ enumerable: false,
193
+ configurable: true
194
+ });
181
195
  Object.defineProperty(SessionRecording.prototype, "status", {
182
196
  /**
183
197
  * defaults to buffering mode until a decide response is received
@@ -261,9 +275,9 @@ var SessionRecording = /** @class */ (function () {
261
275
  _a[SESSION_RECORDING_ENABLED_SERVER_SIDE] = !!response['sessionRecording'],
262
276
  _a[CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE] = (_b = response.sessionRecording) === null || _b === void 0 ? void 0 : _b.consoleLogRecordingEnabled,
263
277
  _a[SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE] = (_c = response.sessionRecording) === null || _c === void 0 ? void 0 : _c.recorderVersion,
278
+ _a[SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE] = (_d = response.sessionRecording) === null || _d === void 0 ? void 0 : _d.networkPayloadCapture,
264
279
  _a));
265
280
  }
266
- this._networkPayloadCapture = (_d = response.sessionRecording) === null || _d === void 0 ? void 0 : _d.networkPayloadCapture;
267
281
  var receivedSampleRate = (_e = response.sessionRecording) === null || _e === void 0 ? void 0 : _e.sampleRate;
268
282
  this._sampleRate =
269
283
  _isUndefined(receivedSampleRate) || _isNull(receivedSampleRate) ? null : parseFloat(receivedSampleRate);
@@ -459,10 +473,8 @@ var SessionRecording = /** @class */ (function () {
459
473
  if (window.rrwebConsoleRecord && this.isConsoleLogCaptureEnabled) {
460
474
  plugins.push(window.rrwebConsoleRecord.getRecordConsolePlugin());
461
475
  }
462
- if (this._networkPayloadCapture) {
463
- if (_isFunction(window.getRecordNetworkPlugin)) {
464
- plugins.push(window.getRecordNetworkPlugin(buildNetworkRequestOptions(this.instance.config, this._networkPayloadCapture)));
465
- }
476
+ if (this.networkPayloadCapture && _isFunction(window.getRecordNetworkPlugin)) {
477
+ plugins.push(window.getRecordNetworkPlugin(buildNetworkRequestOptions(this.instance.config, this.networkPayloadCapture)));
466
478
  }
467
479
  this.stopRrweb = this.rrwebRecord(__assign({ emit: function (event) {
468
480
  _this.onRRwebEmit(event);
@@ -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,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,MAAM,EAAE,MAAM,qBAAqB,CAAA;AAC5C,OAAO,EAAE,0BAA0B,EAAE,MAAM,UAAU,CAAA;AAErD,IAAM,aAAa,GAAG,KAAK,CAAA;AAE3B,MAAM,CAAC,IAAM,kCAAkC,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAA,CAAC,YAAY;AAC5E,MAAM,CAAC,IAAM,wBAAwB,GAAG,IAAI,GAAG,IAAI,GAAG,GAAG,CAAA,CAAC,+BAA+B;AACzF,MAAM,CAAC,IAAM,wBAAwB,GAAG,IAAI,CAAA,CAAC,YAAY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AA;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,AA3kBD,IA2kBC","sourcesContent":["import {\n CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_IS_SAMPLED,\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 private _networkPayloadCapture: Pick<NetworkRecordOptions, 'recordHeaders' | 'recordBody'> | undefined = undefined\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 /**\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 })\n }\n\n this._networkPayloadCapture = response.sessionRecording?.networkPayloadCapture\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) {\n if (_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\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,8CAA8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AAQ,GAAG,IAAI,CAAC,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,4 +1,19 @@
1
1
  import { PersistentStore } from './types';
2
+ /**
3
+ * Browsers don't offer a way to check if something is a public suffix
4
+ * e.g. `.com.au`, `.io`, `.org.uk`
5
+ *
6
+ * But they do reject cookies set on public suffixes
7
+ * Setting a cookie on `.co.uk` would mean it was sent for every `.co.uk` site visited
8
+ *
9
+ * So, we can use this to check if a domain is a public suffix
10
+ * by trying to set a cookie on a subdomain of the provided hostname
11
+ * until the browser accepts it
12
+ *
13
+ * inspired by https://github.com/AngusFu/browser-root-domain
14
+ */
15
+ export declare function seekFirstNonPublicSubDomain(hostname: string, cookieJar?: Document): string;
16
+ export declare function chooseCookieDomain(hostname: string, cross_subdomain: boolean | undefined): string;
2
17
  export declare const cookieStore: PersistentStore;
3
18
  export declare const localStore: PersistentStore;
4
19
  export declare const localPlusCookieStore: PersistentStore;
@@ -13,7 +13,62 @@ import { _extend } from './utils';
13
13
  import { DISTINCT_ID, SESSION_ID, SESSION_RECORDING_IS_SAMPLED } from './constants';
14
14
  import { _isNull, _isUndefined } from './utils/type-utils';
15
15
  import { logger } from './utils/logger';
16
+ import { uuidv7 } from './uuidv7';
17
+ var Y1970 = 'Thu, 01 Jan 1970 00:00:00 GMT';
18
+ /**
19
+ * Browsers don't offer a way to check if something is a public suffix
20
+ * e.g. `.com.au`, `.io`, `.org.uk`
21
+ *
22
+ * But they do reject cookies set on public suffixes
23
+ * Setting a cookie on `.co.uk` would mean it was sent for every `.co.uk` site visited
24
+ *
25
+ * So, we can use this to check if a domain is a public suffix
26
+ * by trying to set a cookie on a subdomain of the provided hostname
27
+ * until the browser accepts it
28
+ *
29
+ * inspired by https://github.com/AngusFu/browser-root-domain
30
+ */
31
+ export function seekFirstNonPublicSubDomain(hostname, cookieJar) {
32
+ if (cookieJar === void 0) { cookieJar = document; }
33
+ if (['localhost', '127.0.0.1'].includes(hostname))
34
+ return '';
35
+ var list = hostname.split('.');
36
+ var len = list.length;
37
+ var key = 'dmn_chk_' + uuidv7();
38
+ var R = new RegExp('(^|;)\\s*' + key + '=1');
39
+ while (len--) {
40
+ var candidate = list.slice(len).join('.');
41
+ var candidateCookieValue = key + '=1;domain=.' + candidate;
42
+ // try to set cookie
43
+ cookieJar.cookie = candidateCookieValue;
44
+ if (R.test(cookieJar.cookie)) {
45
+ // the cookie was accepted by the browser, remove the test cookie
46
+ cookieJar.cookie = candidateCookieValue + ';expires=' + Y1970;
47
+ return candidate;
48
+ }
49
+ }
50
+ return '';
51
+ }
16
52
  var DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;
53
+ var originalCookieDomainFn = function (hostname) {
54
+ var matches = hostname.match(DOMAIN_MATCH_REGEX);
55
+ return matches ? matches[0] : '';
56
+ };
57
+ export function chooseCookieDomain(hostname, cross_subdomain) {
58
+ if (cross_subdomain) {
59
+ // NOTE: Could we use this for cross domain tracking?
60
+ var matchedSubDomain = seekFirstNonPublicSubDomain(hostname);
61
+ if (!matchedSubDomain) {
62
+ var originalMatch = originalCookieDomainFn(hostname);
63
+ if (originalMatch !== matchedSubDomain) {
64
+ logger.info('Warning: cookie subdomain discovery mismatch', originalMatch, matchedSubDomain);
65
+ }
66
+ matchedSubDomain = originalMatch;
67
+ }
68
+ return matchedSubDomain ? '; domain=.' + matchedSubDomain : '';
69
+ }
70
+ return '';
71
+ }
17
72
  // Methods partially borrowed from quirksmode.org/js/cookies.html
18
73
  export var cookieStore = {
19
74
  is_supported: function () { return true; },
@@ -49,12 +104,8 @@ export var cookieStore = {
49
104
  },
50
105
  set: function (name, value, days, cross_subdomain, is_secure) {
51
106
  try {
52
- var cdomain = '', expires = '', secure = '';
53
- if (cross_subdomain) {
54
- // NOTE: Could we use this for cross domain tracking?
55
- var matches = document.location.hostname.match(DOMAIN_MATCH_REGEX), domain = matches ? matches[0] : '';
56
- cdomain = domain ? '; domain=.' + domain : '';
57
- }
107
+ var expires = '', secure = '';
108
+ var cdomain = chooseCookieDomain(document.location.hostname, cross_subdomain);
58
109
  if (days) {
59
110
  var date = new Date();
60
111
  date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
@@ -1 +1 @@
1
- {"version":3,"file":"storage.js","sourceRoot":"","sources":["../../src/storage.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAEjC,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,4BAA4B,EAAE,MAAM,aAAa,CAAA;AAEnF,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAEvC,IAAM,kBAAkB,GAAG,iCAAiC,CAAA;AAE5D,iEAAiE;AACjE,MAAM,CAAC,IAAM,WAAW,GAAoB;IACxC,YAAY,EAAE,cAAM,OAAA,IAAI,EAAJ,CAAI;IAExB,KAAK,EAAE,UAAU,GAAG;QAChB,MAAM,CAAC,KAAK,CAAC,qBAAqB,GAAG,GAAG,CAAC,CAAA;IAC7C,CAAC;IAED,GAAG,EAAE,UAAU,IAAI;QACf,IAAI;YACA,IAAM,MAAM,GAAG,IAAI,GAA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AC,OAAO,GAAG,EAAE;YACV,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;SAC1B;QACD,OAAO,IAAI,CAAA;IACf,CAAC;IAED,KAAK,EAAE,UAAU,IAAI;QACjB,IAAI;YACA,OAAO,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,CAAA;SACpD;QAAC,OAAO,GAAG,EAAE;YACV,OAAO;SACV;QACD,OAAO,IAAI,CAAA;IACf,CAAC;IAED,GAAG,EAAE,UAAU,IAAI,EAAE,KAAK;QACtB,IAAI;YACA,MAAM,CAAC,cAAc,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAA;SAC7D;QAAC,OAAO,GAAG,EAAE;YACV,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;SAC1B;IACL,CAAC;IAED,MAAM,EAAE,UAAU,IAAI;QAClB,IAAI;YACA,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;SACzC;QAAC,OAAO,GAAG,EAAE;YACV,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;SAC1B;IACL,CAAC;CACJ,CAAA","sourcesContent":["import { _extend } from './utils'\nimport { PersistentStore, Properties } from './types'\nimport { DISTINCT_ID, SESSION_ID, SESSION_RECORDING_IS_SAMPLED } from './constants'\n\nimport { _isNull, _isUndefined } from './utils/type-utils'\nimport { logger } from './utils/logger'\n\nconst DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\\.[a-z]{2,}$/i\n\n// Methods partially borrowed from quirksmode.org/js/cookies.html\nexport const cookieStore: PersistentStore = {\n is_supported: () => true,\n\n error: function (msg) {\n logger.error('cookieStore error: ' + msg)\n },\n\n get: function (name) {\n try {\n const nameEQ = name + '='\n const ca = document.cookie.split(';').filter((x) => x.length)\n for (let i = 0; i < ca.length; i++) {\n let c = ca[i]\n while (c.charAt(0) == ' ') {\n c = c.substring(1, c.length)\n }\n if (c.indexOf(nameEQ) === 0) {\n return decodeURIComponent(c.substring(nameEQ.length, c.length))\n }\n }\n } catch (err) {}\n return null\n },\n\n parse: function (name) {\n let cookie\n try {\n cookie = JSON.parse(cookieStore.get(name)) || {}\n } catch (err) {\n // noop\n }\n return cookie\n },\n\n set: function (name, value, days, cross_subdomain, is_secure) {\n try {\n let cdomain = '',\n expires = '',\n secure = ''\n\n if (cross_subdomain) {\n // NOTE: Could we use this for cross domain tracking?\n const matches = document.location.hostname.match(DOMAIN_MATCH_REGEX),\n domain = matches ? matches[0] : ''\n\n cdomain = domain ? '; domain=.' + domain : ''\n }\n\n if (days) {\n const date = new Date()\n date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)\n expires = '; expires=' + date.toUTCString()\n }\n\n if (is_secure) {\n secure = '; secure'\n }\n\n const new_cookie_val =\n name +\n '=' +\n encodeURIComponent(JSON.stringify(value)) +\n expires +\n '; SameSite=Lax; path=/' +\n cdomain +\n secure\n document.cookie = new_cookie_val\n return new_cookie_val\n } catch (err) {\n return\n }\n },\n\n remove: function (name, cross_subdomain) {\n try {\n cookieStore.set(name, '', -1, cross_subdomain)\n } catch (err) {\n return\n }\n },\n}\n\nlet _localStorage_supported: boolean | null = null\n\nexport const localStore: PersistentStore = {\n is_supported: function () {\n if (!_isNull(_localStorage_supported)) {\n return _localStorage_supported\n }\n\n let supported = true\n if (!_isUndefined(window)) {\n try {\n const key = '__mplssupport__',\n val = 'xyz'\n localStore.set(key, val)\n if (localStore.get(key) !== '\"xyz\"') {\n supported = false\n }\n localStore.remove(key)\n } catch (err) {\n supported = false\n }\n } else {\n supported = false\n }\n if (!supported) {\n logger.error('localStorage unsupported; falling back to cookie store')\n }\n\n _localStorage_supported = supported\n return supported\n },\n\n error: function (msg) {\n logger.error('localStorage error: ' + msg)\n },\n\n get: function (name) {\n try {\n return window.localStorage.getItem(name)\n } catch (err) {\n localStore.error(err)\n }\n return null\n },\n\n parse: function (name) {\n try {\n return JSON.parse(localStore.get(name)) || {}\n } catch (err) {\n // noop\n }\n return null\n },\n\n set: function (name, value) {\n try {\n window.localStorage.setItem(name, JSON.stringify(value))\n } catch (err) {\n localStore.error(err)\n }\n },\n\n remove: function (name) {\n try {\n window.localStorage.removeItem(name)\n } catch (err) {\n localStore.error(err)\n }\n },\n}\n\n// Use localstorage for most data but still use cookie for COOKIE_PERSISTED_PROPERTIES\n// This solves issues with cookies having too much data in them causing headers too large\n// Also makes sure we don't have to send a ton of data to the server\nconst COOKIE_PERSISTED_PROPERTIES = [DISTINCT_ID, SESSION_ID, SESSION_RECORDING_IS_SAMPLED]\n\nexport const localPlusCookieStore: PersistentStore = {\n ...localStore,\n parse: function (name) {\n try {\n let extend: Properties = {}\n try {\n // See if there's a cookie stored with data.\n extend = cookieStore.parse(name) || {}\n } catch (err) {}\n const value = _extend(extend, JSON.parse(localStore.get(name) || '{}'))\n localStore.set(name, value)\n return value\n } catch (err) {\n // noop\n }\n return null\n },\n\n set: function (name, value, days, cross_subdomain, is_secure) {\n try {\n localStore.set(name, value)\n const cookiePersistedProperties: Record<string, any> = {}\n COOKIE_PERSISTED_PROPERTIES.forEach((key) => {\n if (value[key]) {\n cookiePersistedProperties[key] = value[key]\n }\n })\n\n if (Object.keys(cookiePersistedProperties).length) {\n cookieStore.set(name, cookiePersistedProperties, days, cross_subdomain, is_secure)\n }\n } catch (err) {\n localStore.error(err)\n }\n },\n\n remove: function (name, cross_subdomain) {\n try {\n window.localStorage.removeItem(name)\n cookieStore.remove(name, cross_subdomain)\n } catch (err) {\n localStore.error(err)\n }\n },\n}\n\nconst memoryStorage: Properties = {}\n\n// Storage that only lasts the length of the pageview if we don't want to use cookies\nexport const memoryStore: PersistentStore = {\n is_supported: function () {\n return true\n },\n\n error: function (msg) {\n logger.error('memoryStorage error: ' + msg)\n },\n\n get: function (name) {\n return memoryStorage[name] || null\n },\n\n parse: function (name) {\n return memoryStorage[name] || null\n },\n\n set: function (name, value) {\n memoryStorage[name] = value\n },\n\n remove: function (name) {\n delete memoryStorage[name]\n },\n}\n\nlet sessionStorageSupported: boolean | null = null\nexport const resetSessionStorageSupported = () => {\n sessionStorageSupported = null\n}\n// Storage that only lasts the length of a tab/window. Survives page refreshes\nexport const sessionStore: PersistentStore = {\n is_supported: function () {\n if (!_isNull(sessionStorageSupported)) {\n return sessionStorageSupported\n }\n sessionStorageSupported = true\n if (!_isUndefined(window)) {\n try {\n const key = '__support__',\n val = 'xyz'\n sessionStore.set(key, val)\n if (sessionStore.get(key) !== '\"xyz\"') {\n sessionStorageSupported = false\n }\n sessionStore.remove(key)\n } catch (err) {\n sessionStorageSupported = false\n }\n } else {\n sessionStorageSupported = false\n }\n return sessionStorageSupported\n },\n\n error: function (msg) {\n logger.error('sessionStorage error: ', msg)\n },\n\n get: function (name) {\n try {\n return window.sessionStorage.getItem(name)\n } catch (err) {\n sessionStore.error(err)\n }\n return null\n },\n\n parse: function (name) {\n try {\n return JSON.parse(sessionStore.get(name)) || null\n } catch (err) {\n // noop\n }\n return null\n },\n\n set: function (name, value) {\n try {\n window.sessionStorage.setItem(name, JSON.stringify(value))\n } catch (err) {\n sessionStore.error(err)\n }\n },\n\n remove: function (name) {\n try {\n window.sessionStorage.removeItem(name)\n } catch (err) {\n sessionStore.error(err)\n }\n },\n}\n"]}
1
+ {"version":3,"file":"storage.js","sourceRoot":"","sources":["../../src/storage.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAEjC,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,4BAA4B,EAAE,MAAM,aAAa,CAAA;AAEnF,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AACvC,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AAEjC,IAAM,KAAK,GAAG,+BAA+B,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V,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;SAC1B;IACL,CAAC;CACJ,CAAA","sourcesContent":["import { _extend } from './utils'\nimport { PersistentStore, Properties } from './types'\nimport { DISTINCT_ID, SESSION_ID, SESSION_RECORDING_IS_SAMPLED } from './constants'\n\nimport { _isNull, _isUndefined } from './utils/type-utils'\nimport { logger } from './utils/logger'\nimport { uuidv7 } from './uuidv7'\n\nconst Y1970 = 'Thu, 01 Jan 1970 00:00:00 GMT'\n\n/**\n * Browsers don't offer a way to check if something is a public suffix\n * e.g. `.com.au`, `.io`, `.org.uk`\n *\n * But they do reject cookies set on public suffixes\n * Setting a cookie on `.co.uk` would mean it was sent for every `.co.uk` site visited\n *\n * So, we can use this to check if a domain is a public suffix\n * by trying to set a cookie on a subdomain of the provided hostname\n * until the browser accepts it\n *\n * inspired by https://github.com/AngusFu/browser-root-domain\n */\nexport function seekFirstNonPublicSubDomain(hostname: string, cookieJar = document): string {\n if (['localhost', '127.0.0.1'].includes(hostname)) return ''\n\n const list = hostname.split('.')\n let len = list.length\n const key = 'dmn_chk_' + uuidv7()\n const R = new RegExp('(^|;)\\\\s*' + key + '=1')\n\n while (len--) {\n const candidate = list.slice(len).join('.')\n const candidateCookieValue = key + '=1;domain=.' + candidate\n\n // try to set cookie\n cookieJar.cookie = candidateCookieValue\n\n if (R.test(cookieJar.cookie)) {\n // the cookie was accepted by the browser, remove the test cookie\n cookieJar.cookie = candidateCookieValue + ';expires=' + Y1970\n return candidate\n }\n }\n return ''\n}\n\nconst DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\\.[a-z]{2,}$/i\nconst originalCookieDomainFn = (hostname: string): string => {\n const matches = hostname.match(DOMAIN_MATCH_REGEX)\n return matches ? matches[0] : ''\n}\n\nexport function chooseCookieDomain(hostname: string, cross_subdomain: boolean | undefined): string {\n if (cross_subdomain) {\n // NOTE: Could we use this for cross domain tracking?\n let matchedSubDomain = seekFirstNonPublicSubDomain(hostname)\n\n if (!matchedSubDomain) {\n const originalMatch = originalCookieDomainFn(hostname)\n if (originalMatch !== matchedSubDomain) {\n logger.info('Warning: cookie subdomain discovery mismatch', originalMatch, matchedSubDomain)\n }\n matchedSubDomain = originalMatch\n }\n\n return matchedSubDomain ? '; domain=.' + matchedSubDomain : ''\n }\n return ''\n}\n\n// Methods partially borrowed from quirksmode.org/js/cookies.html\nexport const cookieStore: PersistentStore = {\n is_supported: () => true,\n\n error: function (msg) {\n logger.error('cookieStore error: ' + msg)\n },\n\n get: function (name) {\n try {\n const nameEQ = name + '='\n const ca = document.cookie.split(';').filter((x) => x.length)\n for (let i = 0; i < ca.length; i++) {\n let c = ca[i]\n while (c.charAt(0) == ' ') {\n c = c.substring(1, c.length)\n }\n if (c.indexOf(nameEQ) === 0) {\n return decodeURIComponent(c.substring(nameEQ.length, c.length))\n }\n }\n } catch (err) {}\n return null\n },\n\n parse: function (name) {\n let cookie\n try {\n cookie = JSON.parse(cookieStore.get(name)) || {}\n } catch (err) {\n // noop\n }\n return cookie\n },\n\n set: function (name, value, days, cross_subdomain, is_secure) {\n try {\n let expires = '',\n secure = ''\n\n const cdomain = chooseCookieDomain(document.location.hostname, cross_subdomain)\n\n if (days) {\n const date = new Date()\n date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)\n expires = '; expires=' + date.toUTCString()\n }\n\n if (is_secure) {\n secure = '; secure'\n }\n\n const new_cookie_val =\n name +\n '=' +\n encodeURIComponent(JSON.stringify(value)) +\n expires +\n '; SameSite=Lax; path=/' +\n cdomain +\n secure\n document.cookie = new_cookie_val\n return new_cookie_val\n } catch (err) {\n return\n }\n },\n\n remove: function (name, cross_subdomain) {\n try {\n cookieStore.set(name, '', -1, cross_subdomain)\n } catch (err) {\n return\n }\n },\n}\n\nlet _localStorage_supported: boolean | null = null\n\nexport const localStore: PersistentStore = {\n is_supported: function () {\n if (!_isNull(_localStorage_supported)) {\n return _localStorage_supported\n }\n\n let supported = true\n if (!_isUndefined(window)) {\n try {\n const key = '__mplssupport__',\n val = 'xyz'\n localStore.set(key, val)\n if (localStore.get(key) !== '\"xyz\"') {\n supported = false\n }\n localStore.remove(key)\n } catch (err) {\n supported = false\n }\n } else {\n supported = false\n }\n if (!supported) {\n logger.error('localStorage unsupported; falling back to cookie store')\n }\n\n _localStorage_supported = supported\n return supported\n },\n\n error: function (msg) {\n logger.error('localStorage error: ' + msg)\n },\n\n get: function (name) {\n try {\n return window.localStorage.getItem(name)\n } catch (err) {\n localStore.error(err)\n }\n return null\n },\n\n parse: function (name) {\n try {\n return JSON.parse(localStore.get(name)) || {}\n } catch (err) {\n // noop\n }\n return null\n },\n\n set: function (name, value) {\n try {\n window.localStorage.setItem(name, JSON.stringify(value))\n } catch (err) {\n localStore.error(err)\n }\n },\n\n remove: function (name) {\n try {\n window.localStorage.removeItem(name)\n } catch (err) {\n localStore.error(err)\n }\n },\n}\n\n// Use localstorage for most data but still use cookie for COOKIE_PERSISTED_PROPERTIES\n// This solves issues with cookies having too much data in them causing headers too large\n// Also makes sure we don't have to send a ton of data to the server\nconst COOKIE_PERSISTED_PROPERTIES = [DISTINCT_ID, SESSION_ID, SESSION_RECORDING_IS_SAMPLED]\n\nexport const localPlusCookieStore: PersistentStore = {\n ...localStore,\n parse: function (name) {\n try {\n let extend: Properties = {}\n try {\n // See if there's a cookie stored with data.\n extend = cookieStore.parse(name) || {}\n } catch (err) {}\n const value = _extend(extend, JSON.parse(localStore.get(name) || '{}'))\n localStore.set(name, value)\n return value\n } catch (err) {\n // noop\n }\n return null\n },\n\n set: function (name, value, days, cross_subdomain, is_secure) {\n try {\n localStore.set(name, value)\n const cookiePersistedProperties: Record<string, any> = {}\n COOKIE_PERSISTED_PROPERTIES.forEach((key) => {\n if (value[key]) {\n cookiePersistedProperties[key] = value[key]\n }\n })\n\n if (Object.keys(cookiePersistedProperties).length) {\n cookieStore.set(name, cookiePersistedProperties, days, cross_subdomain, is_secure)\n }\n } catch (err) {\n localStore.error(err)\n }\n },\n\n remove: function (name, cross_subdomain) {\n try {\n window.localStorage.removeItem(name)\n cookieStore.remove(name, cross_subdomain)\n } catch (err) {\n localStore.error(err)\n }\n },\n}\n\nconst memoryStorage: Properties = {}\n\n// Storage that only lasts the length of the pageview if we don't want to use cookies\nexport const memoryStore: PersistentStore = {\n is_supported: function () {\n return true\n },\n\n error: function (msg) {\n logger.error('memoryStorage error: ' + msg)\n },\n\n get: function (name) {\n return memoryStorage[name] || null\n },\n\n parse: function (name) {\n return memoryStorage[name] || null\n },\n\n set: function (name, value) {\n memoryStorage[name] = value\n },\n\n remove: function (name) {\n delete memoryStorage[name]\n },\n}\n\nlet sessionStorageSupported: boolean | null = null\nexport const resetSessionStorageSupported = () => {\n sessionStorageSupported = null\n}\n// Storage that only lasts the length of a tab/window. Survives page refreshes\nexport const sessionStore: PersistentStore = {\n is_supported: function () {\n if (!_isNull(sessionStorageSupported)) {\n return sessionStorageSupported\n }\n sessionStorageSupported = true\n if (!_isUndefined(window)) {\n try {\n const key = '__support__',\n val = 'xyz'\n sessionStore.set(key, val)\n if (sessionStore.get(key) !== '\"xyz\"') {\n sessionStorageSupported = false\n }\n sessionStore.remove(key)\n } catch (err) {\n sessionStorageSupported = false\n }\n } else {\n sessionStorageSupported = false\n }\n return sessionStorageSupported\n },\n\n error: function (msg) {\n logger.error('sessionStorage error: ', msg)\n },\n\n get: function (name) {\n try {\n return window.sessionStorage.getItem(name)\n } catch (err) {\n sessionStore.error(err)\n }\n return null\n },\n\n parse: function (name) {\n try {\n return JSON.parse(sessionStore.get(name)) || null\n } catch (err) {\n // noop\n }\n return null\n },\n\n set: function (name, value) {\n try {\n window.sessionStorage.setItem(name, JSON.stringify(value))\n } catch (err) {\n sessionStore.error(err)\n }\n },\n\n remove: function (name) {\n try {\n window.sessionStorage.removeItem(name)\n } catch (err) {\n sessionStore.error(err)\n }\n },\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "posthog-js",
3
- "version": "1.90.0",
3
+ "version": "1.90.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",