posthog-js 1.76.0 → 1.77.1

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 (129) hide show
  1. package/dist/array.full.js +2 -2
  2. package/dist/array.full.js.map +1 -1
  3. package/dist/array.js +2 -2
  4. package/dist/array.js.map +1 -1
  5. package/dist/es.js +2 -2
  6. package/dist/es.js.map +1 -1
  7. package/dist/module.d.ts +38 -6
  8. package/dist/module.js +2 -2
  9. package/dist/module.js.map +1 -1
  10. package/lib/package.json +8 -6
  11. package/lib/src/autocapture-utils.d.ts +15 -0
  12. package/lib/src/autocapture-utils.js +303 -0
  13. package/lib/src/autocapture-utils.js.map +1 -0
  14. package/lib/src/autocapture.d.ts +27 -0
  15. package/lib/src/autocapture.js +290 -0
  16. package/lib/src/autocapture.js.map +1 -0
  17. package/lib/src/base-request-queue.d.ts +12 -0
  18. package/lib/src/base-request-queue.js +33 -0
  19. package/lib/src/base-request-queue.js.map +1 -0
  20. package/lib/src/compression.d.ts +3 -0
  21. package/lib/src/compression.js +35 -0
  22. package/lib/src/compression.js.map +1 -0
  23. package/lib/src/config.d.ts +5 -0
  24. package/lib/src/config.js +9 -0
  25. package/lib/src/config.js.map +1 -0
  26. package/lib/src/constants.d.ts +19 -0
  27. package/lib/src/constants.js +41 -0
  28. package/lib/src/constants.js.map +1 -0
  29. package/lib/src/decide.d.ts +8 -0
  30. package/lib/src/decide.js +118 -0
  31. package/lib/src/decide.js.map +1 -0
  32. package/lib/src/extensions/cloud.d.ts +1 -0
  33. package/lib/src/extensions/cloud.js +2 -0
  34. package/lib/src/extensions/cloud.js.map +1 -0
  35. package/lib/src/extensions/exceptions/error-conversion.d.ts +26 -0
  36. package/lib/src/extensions/exceptions/error-conversion.js +204 -0
  37. package/lib/src/extensions/exceptions/error-conversion.js.map +1 -0
  38. package/lib/src/extensions/exceptions/exception-autocapture.d.ts +24 -0
  39. package/lib/src/extensions/exceptions/exception-autocapture.js +164 -0
  40. package/lib/src/extensions/exceptions/exception-autocapture.js.map +1 -0
  41. package/lib/src/extensions/exceptions/stack-trace.d.ts +31 -0
  42. package/lib/src/extensions/exceptions/stack-trace.js +259 -0
  43. package/lib/src/extensions/exceptions/stack-trace.js.map +1 -0
  44. package/lib/src/extensions/exceptions/type-checking.d.ts +10 -0
  45. package/lib/src/extensions/exceptions/type-checking.js +43 -0
  46. package/lib/src/extensions/exceptions/type-checking.js.map +1 -0
  47. package/lib/src/extensions/rageclick.d.ts +10 -0
  48. package/lib/src/extensions/rageclick.js +33 -0
  49. package/lib/src/extensions/rageclick.js.map +1 -0
  50. package/lib/src/extensions/segment-integration.d.ts +44 -0
  51. package/lib/src/extensions/segment-integration.js +34 -0
  52. package/lib/src/extensions/segment-integration.js.map +1 -0
  53. package/lib/src/extensions/sentry-integration.d.ts +30 -0
  54. package/lib/src/extensions/sentry-integration.js +63 -0
  55. package/lib/src/extensions/sentry-integration.js.map +1 -0
  56. package/lib/src/extensions/sessionrecording-utils.d.ts +67 -0
  57. package/lib/src/extensions/sessionrecording-utils.js +192 -0
  58. package/lib/src/extensions/sessionrecording-utils.js.map +1 -0
  59. package/lib/src/extensions/sessionrecording.d.ts +45 -0
  60. package/lib/src/extensions/sessionrecording.js +430 -0
  61. package/lib/src/extensions/sessionrecording.js.map +1 -0
  62. package/lib/src/extensions/toolbar.d.ts +18 -0
  63. package/lib/src/extensions/toolbar.js +151 -0
  64. package/lib/src/extensions/toolbar.js.map +1 -0
  65. package/lib/src/extensions/web-performance.d.ts +20 -0
  66. package/lib/src/extensions/web-performance.js +245 -0
  67. package/lib/src/extensions/web-performance.js.map +1 -0
  68. package/lib/src/gdpr-utils.d.ts +80 -0
  69. package/lib/src/gdpr-utils.js +236 -0
  70. package/lib/src/gdpr-utils.js.map +1 -0
  71. package/lib/src/loader-globals-full.d.ts +1 -0
  72. package/lib/src/loader-globals-full.js +5 -0
  73. package/lib/src/loader-globals-full.js.map +1 -0
  74. package/lib/src/loader-globals.d.ts +1 -0
  75. package/lib/src/loader-globals.js +3 -0
  76. package/lib/src/loader-globals.js.map +1 -0
  77. package/lib/src/loader-module.d.ts +4 -0
  78. package/lib/src/loader-module.js +6 -0
  79. package/lib/src/loader-module.js.map +1 -0
  80. package/lib/src/loader-recorder-v2.d.ts +2 -0
  81. package/lib/src/loader-recorder-v2.js +15 -0
  82. package/lib/src/loader-recorder-v2.js.map +1 -0
  83. package/lib/src/loader-recorder.d.ts +2 -0
  84. package/lib/src/loader-recorder.js +15 -0
  85. package/lib/src/loader-recorder.js.map +1 -0
  86. package/lib/src/page-view.d.ts +38 -0
  87. package/lib/src/page-view.js +127 -0
  88. package/lib/src/page-view.js.map +1 -0
  89. package/lib/src/posthog-core.d.ts +701 -0
  90. package/lib/src/posthog-core.js +1916 -0
  91. package/lib/src/posthog-core.js.map +1 -0
  92. package/lib/src/posthog-featureflags.d.ts +70 -0
  93. package/lib/src/posthog-featureflags.js +438 -0
  94. package/lib/src/posthog-featureflags.js.map +1 -0
  95. package/lib/src/posthog-persistence.d.ts +57 -0
  96. package/lib/src/posthog-persistence.js +256 -0
  97. package/lib/src/posthog-persistence.js.map +1 -0
  98. package/lib/src/posthog-surveys.d.ts +57 -0
  99. package/lib/src/posthog-surveys.js +76 -0
  100. package/lib/src/posthog-surveys.js.map +1 -0
  101. package/lib/src/rate-limiter.d.ts +5 -0
  102. package/lib/src/rate-limiter.js +66 -0
  103. package/lib/src/rate-limiter.js.map +1 -0
  104. package/lib/src/request-queue.d.ts +10 -0
  105. package/lib/src/request-queue.js +146 -0
  106. package/lib/src/request-queue.js.map +1 -0
  107. package/lib/src/retry-queue.d.ts +28 -0
  108. package/lib/src/retry-queue.js +198 -0
  109. package/lib/src/retry-queue.js.map +1 -0
  110. package/lib/src/send-request.d.ts +6 -0
  111. package/lib/src/send-request.js +125 -0
  112. package/lib/src/send-request.js.map +1 -0
  113. package/lib/src/sessionid.d.ts +28 -0
  114. package/lib/src/sessionid.js +205 -0
  115. package/lib/src/sessionid.js.map +1 -0
  116. package/lib/src/storage.d.ts +7 -0
  117. package/lib/src/storage.js +291 -0
  118. package/lib/src/storage.js.map +1 -0
  119. package/lib/src/types.d.ts +294 -0
  120. package/lib/src/types.js +6 -0
  121. package/lib/src/types.js.map +1 -0
  122. package/lib/src/utils.d.ts +89 -0
  123. package/lib/src/utils.js +868 -0
  124. package/lib/src/utils.js.map +1 -0
  125. package/lib/src/uuidv7.d.ts +42 -0
  126. package/lib/src/uuidv7.js +228 -0
  127. package/lib/src/uuidv7.js.map +1 -0
  128. package/package.json +8 -6
  129. package/CHANGELOG.md +0 -1145
@@ -0,0 +1,430 @@
1
+ var __assign = (this && this.__assign) || function () {
2
+ __assign = Object.assign || function(t) {
3
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
4
+ s = arguments[i];
5
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
+ t[p] = s[p];
7
+ }
8
+ return t;
9
+ };
10
+ return __assign.apply(this, arguments);
11
+ };
12
+ var __values = (this && this.__values) || function(o) {
13
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
14
+ if (m) return m.call(o);
15
+ if (o && typeof o.length === "number") return {
16
+ next: function () {
17
+ if (o && i >= o.length) o = void 0;
18
+ return { value: o && o[i++], done: !o };
19
+ }
20
+ };
21
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
22
+ };
23
+ var __read = (this && this.__read) || function (o, n) {
24
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
25
+ if (!m) return o;
26
+ var i = m.call(o), r, ar = [], e;
27
+ try {
28
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
29
+ }
30
+ catch (error) { e = { error: error }; }
31
+ finally {
32
+ try {
33
+ if (r && !r.done && (m = i["return"])) m.call(i);
34
+ }
35
+ finally { if (e) throw e.error; }
36
+ }
37
+ return ar;
38
+ };
39
+ import { CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE, SESSION_RECORDING_ENABLED_SERVER_SIDE, SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE, } from '../constants';
40
+ import { ensureMaxMessageSize, FULL_SNAPSHOT_EVENT_TYPE, INCREMENTAL_SNAPSHOT_EVENT_TYPE, META_EVENT_TYPE, MutationRateLimiter, truncateLargeConsoleLogs, } from './sessionrecording-utils';
41
+ import Config from '../config';
42
+ import { logger, loadScript, _timestamp } from '../utils';
43
+ var BASE_ENDPOINT = '/s/';
44
+ export var RECORDING_IDLE_ACTIVITY_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
45
+ export var RECORDING_MAX_EVENT_SIZE = 1024 * 1024 * 0.9; // ~1mb (with some wiggle room)
46
+ export var RECORDING_BUFFER_TIMEOUT = 2000; // 2 seconds
47
+ export var SESSION_RECORDING_BATCH_KEY = 'sessionRecording';
48
+ // NOTE: Importing this type is problematic as we can't safely bundle it to a TS definition so, instead we redefine.
49
+ // import type { record } from 'rrweb2/typings'
50
+ // import type { recordOptions } from 'rrweb/typings/types'
51
+ // Copied from rrweb typings to avoid import
52
+ var IncrementalSource;
53
+ (function (IncrementalSource) {
54
+ IncrementalSource[IncrementalSource["Mutation"] = 0] = "Mutation";
55
+ IncrementalSource[IncrementalSource["MouseMove"] = 1] = "MouseMove";
56
+ IncrementalSource[IncrementalSource["MouseInteraction"] = 2] = "MouseInteraction";
57
+ IncrementalSource[IncrementalSource["Scroll"] = 3] = "Scroll";
58
+ IncrementalSource[IncrementalSource["ViewportResize"] = 4] = "ViewportResize";
59
+ IncrementalSource[IncrementalSource["Input"] = 5] = "Input";
60
+ IncrementalSource[IncrementalSource["TouchMove"] = 6] = "TouchMove";
61
+ IncrementalSource[IncrementalSource["MediaInteraction"] = 7] = "MediaInteraction";
62
+ IncrementalSource[IncrementalSource["StyleSheetRule"] = 8] = "StyleSheetRule";
63
+ IncrementalSource[IncrementalSource["CanvasMutation"] = 9] = "CanvasMutation";
64
+ IncrementalSource[IncrementalSource["Font"] = 10] = "Font";
65
+ IncrementalSource[IncrementalSource["Log"] = 11] = "Log";
66
+ IncrementalSource[IncrementalSource["Drag"] = 12] = "Drag";
67
+ IncrementalSource[IncrementalSource["StyleDeclaration"] = 13] = "StyleDeclaration";
68
+ IncrementalSource[IncrementalSource["Selection"] = 14] = "Selection";
69
+ IncrementalSource[IncrementalSource["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
70
+ })(IncrementalSource || (IncrementalSource = {}));
71
+ var ACTIVE_SOURCES = [
72
+ IncrementalSource.MouseMove,
73
+ IncrementalSource.MouseInteraction,
74
+ IncrementalSource.Scroll,
75
+ IncrementalSource.ViewportResize,
76
+ IncrementalSource.Input,
77
+ IncrementalSource.TouchMove,
78
+ IncrementalSource.MediaInteraction,
79
+ IncrementalSource.Drag,
80
+ ];
81
+ var SessionRecording = /** @class */ (function () {
82
+ function SessionRecording(instance) {
83
+ var _this = this;
84
+ this.lastActivityTimestamp = Date.now();
85
+ this.isIdle = false;
86
+ this.instance = instance;
87
+ this.captureStarted = false;
88
+ this.snapshots = [];
89
+ this.emit = false; // Controls whether data is sent to the server or not
90
+ this.endpoint = BASE_ENDPOINT;
91
+ this.stopRrweb = undefined;
92
+ this.windowId = null;
93
+ this.sessionId = null;
94
+ this.receivedDecide = false;
95
+ window.addEventListener('beforeunload', function () {
96
+ _this._flushBuffer();
97
+ });
98
+ }
99
+ SessionRecording.prototype.startRecordingIfEnabled = function () {
100
+ if (this.isRecordingEnabled()) {
101
+ this.startCaptureAndTrySendingQueuedSnapshots();
102
+ }
103
+ else {
104
+ this.stopRecording();
105
+ }
106
+ };
107
+ SessionRecording.prototype.started = function () {
108
+ return this.captureStarted;
109
+ };
110
+ SessionRecording.prototype.stopRecording = function () {
111
+ if (this.captureStarted && this.stopRrweb) {
112
+ this.stopRrweb();
113
+ this.stopRrweb = undefined;
114
+ this.captureStarted = false;
115
+ }
116
+ };
117
+ SessionRecording.prototype.isRecordingEnabled = function () {
118
+ var enabled_server_side = !!this.instance.get_property(SESSION_RECORDING_ENABLED_SERVER_SIDE);
119
+ var enabled_client_side = !this.instance.get_config('disable_session_recording');
120
+ return enabled_server_side && enabled_client_side;
121
+ };
122
+ SessionRecording.prototype.isConsoleLogCaptureEnabled = function () {
123
+ var enabled_server_side = !!this.instance.get_property(CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE);
124
+ var enabled_client_side = this.instance.get_config('enable_recording_console_log');
125
+ return enabled_client_side !== null && enabled_client_side !== void 0 ? enabled_client_side : enabled_server_side;
126
+ };
127
+ SessionRecording.prototype.getRecordingVersion = function () {
128
+ var _a;
129
+ var recordingVersion_server_side = this.instance.get_property(SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE);
130
+ var recordingVersion_client_side = (_a = this.instance.get_config('session_recording')) === null || _a === void 0 ? void 0 : _a.recorderVersion;
131
+ return recordingVersion_client_side || recordingVersion_server_side || 'v1';
132
+ };
133
+ SessionRecording.prototype.afterDecideResponse = function (response) {
134
+ var _a;
135
+ var _b, _c, _d, _e, _f;
136
+ this.receivedDecide = true;
137
+ if (this.instance.persistence) {
138
+ this.instance.persistence.register((_a = {},
139
+ _a[SESSION_RECORDING_ENABLED_SERVER_SIDE] = !!response['sessionRecording'],
140
+ _a[CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE] = (_b = response.sessionRecording) === null || _b === void 0 ? void 0 : _b.consoleLogRecordingEnabled,
141
+ _a[SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE] = (_c = response.sessionRecording) === null || _c === void 0 ? void 0 : _c.recorderVersion,
142
+ _a));
143
+ }
144
+ if ((_d = response.sessionRecording) === null || _d === void 0 ? void 0 : _d.endpoint) {
145
+ this.endpoint = (_e = response.sessionRecording) === null || _e === void 0 ? void 0 : _e.endpoint;
146
+ }
147
+ if ((_f = response.sessionRecording) === null || _f === void 0 ? void 0 : _f.recorderVersion) {
148
+ this.recorderVersion = response.sessionRecording.recorderVersion;
149
+ }
150
+ this.startRecordingIfEnabled();
151
+ };
152
+ SessionRecording.prototype.log = function (message, level) {
153
+ var _a;
154
+ if (level === void 0) { level = 'log'; }
155
+ (_a = this.instance.sessionRecording) === null || _a === void 0 ? void 0 : _a.onRRwebEmit({
156
+ type: 6,
157
+ data: {
158
+ plugin: 'rrweb/console@1',
159
+ payload: {
160
+ level: level,
161
+ trace: [],
162
+ // Even though it is a string we stringify it as thats what rrweb expects
163
+ payload: [JSON.stringify(message)],
164
+ },
165
+ },
166
+ timestamp: _timestamp(),
167
+ });
168
+ };
169
+ SessionRecording.prototype.startCaptureAndTrySendingQueuedSnapshots = function () {
170
+ var _this = this;
171
+ // Only submit data after we've received a decide response to account for
172
+ // changing endpoints and the feature being disabled on the server side.
173
+ if (this.receivedDecide) {
174
+ this.emit = true;
175
+ this.snapshots.forEach(function (properties) { return _this._captureSnapshotBuffered(properties); });
176
+ }
177
+ this._startCapture();
178
+ };
179
+ SessionRecording.prototype._startCapture = function () {
180
+ var _this = this;
181
+ // According to the rrweb docs, rrweb is not supported on IE11 and below:
182
+ // "rrweb does not support IE11 and below because it uses the MutationObserver API which was supported by these browsers."
183
+ // https://github.com/rrweb-io/rrweb/blob/master/guide.md#compatibility-note
184
+ //
185
+ // However, MutationObserver does exist on IE11, it just doesn't work well and does not detect all changes.
186
+ // Instead, when we load "recorder.js", the first JS error is about "Object.assign" being undefined.
187
+ // Thus instead of MutationObserver, we look for this function and block recording if it's undefined.
188
+ if (typeof Object.assign === 'undefined') {
189
+ return;
190
+ }
191
+ // We do not switch recorder versions midway through a recording.
192
+ if (this.captureStarted || this.instance.get_config('disable_session_recording')) {
193
+ return;
194
+ }
195
+ this.captureStarted = true;
196
+ // We want to ensure the sessionManager is reset if necessary on load of the recorder
197
+ this.instance.sessionManager.checkAndGetSessionAndWindowId();
198
+ var recorderJS = this.getRecordingVersion() === 'v2' ? 'recorder-v2.js' : 'recorder.js';
199
+ // If recorder.js is already loaded (if array.full.js snippet is used or posthog-js/dist/recorder is
200
+ // imported) or matches the requested recorder version, don't load script. Otherwise, remotely import
201
+ // recorder.js from cdn since it hasn't been loaded.
202
+ if (this.instance.__loaded_recorder_version !== this.getRecordingVersion()) {
203
+ loadScript(this.instance.get_config('api_host') + "/static/".concat(recorderJS, "?v=").concat(Config.LIB_VERSION), function (err) {
204
+ if (err) {
205
+ return logger.error("Could not load ".concat(recorderJS), err);
206
+ }
207
+ _this._onScriptLoaded();
208
+ });
209
+ }
210
+ else {
211
+ this._onScriptLoaded();
212
+ }
213
+ };
214
+ SessionRecording.prototype._isInteractiveEvent = function (event) {
215
+ var _a;
216
+ return event.type === INCREMENTAL_SNAPSHOT_EVENT_TYPE && ACTIVE_SOURCES.indexOf((_a = event.data) === null || _a === void 0 ? void 0 : _a.source) !== -1;
217
+ };
218
+ SessionRecording.prototype._updateWindowAndSessionIds = function (event) {
219
+ // Some recording events are triggered by non-user events (e.g. "X minutes ago" text updating on the screen).
220
+ // We don't want to extend the session or trigger a new session in these cases. These events are designated by event
221
+ // type -> incremental update, and source -> mutation.
222
+ var isUserInteraction = this._isInteractiveEvent(event);
223
+ if (!isUserInteraction && !this.isIdle) {
224
+ // We check if the lastActivityTimestamp is old enough to go idle
225
+ if (event.timestamp - this.lastActivityTimestamp > RECORDING_IDLE_ACTIVITY_TIMEOUT_MS) {
226
+ this.isIdle = true;
227
+ }
228
+ }
229
+ if (isUserInteraction) {
230
+ this.lastActivityTimestamp = event.timestamp;
231
+ if (this.isIdle) {
232
+ // Remove the idle state if set and trigger a full snapshot as we will have ingored previous mutations
233
+ this.isIdle = false;
234
+ this._tryTakeFullSnapshot();
235
+ }
236
+ }
237
+ if (this.isIdle) {
238
+ return;
239
+ }
240
+ // We only want to extend the session if it is an interactive event.
241
+ var _a = this.instance.sessionManager.checkAndGetSessionAndWindowId(!isUserInteraction, event.timestamp), windowId = _a.windowId, sessionId = _a.sessionId;
242
+ if ([FULL_SNAPSHOT_EVENT_TYPE, META_EVENT_TYPE].indexOf(event.type) === -1 &&
243
+ (this.windowId !== windowId || this.sessionId !== sessionId)) {
244
+ this._tryTakeFullSnapshot();
245
+ }
246
+ this.windowId = windowId;
247
+ this.sessionId = sessionId;
248
+ };
249
+ SessionRecording.prototype._tryTakeFullSnapshot = function () {
250
+ var _a;
251
+ if (!this.captureStarted) {
252
+ return false;
253
+ }
254
+ try {
255
+ (_a = this.rrwebRecord) === null || _a === void 0 ? void 0 : _a.takeFullSnapshot();
256
+ return true;
257
+ }
258
+ catch (e) {
259
+ // Sometimes a race can occur where the recorder is not fully started yet, so we can't take a full snapshot.
260
+ logger.error('Error taking full snapshot.', e);
261
+ return false;
262
+ }
263
+ };
264
+ SessionRecording.prototype._onScriptLoaded = function () {
265
+ var e_1, _a;
266
+ var _this = this;
267
+ var _b;
268
+ // rrweb config info: https://github.com/rrweb-io/rrweb/blob/7d5d0033258d6c29599fb08412202d9a2c7b9413/src/record/index.ts#L28
269
+ var sessionRecordingOptions = {
270
+ // select set of rrweb config options we expose to our users
271
+ // see https://github.com/rrweb-io/rrweb/blob/master/guide.md
272
+ blockClass: 'ph-no-capture',
273
+ blockSelector: undefined,
274
+ ignoreClass: 'ph-ignore-input',
275
+ maskTextClass: 'ph-mask',
276
+ maskTextSelector: undefined,
277
+ maskTextFn: undefined,
278
+ maskAllInputs: true,
279
+ maskInputOptions: {},
280
+ maskInputFn: undefined,
281
+ slimDOMOptions: {},
282
+ collectFonts: false,
283
+ inlineStylesheet: true,
284
+ recordCrossOriginIframes: false,
285
+ };
286
+ // We switched from loading all of rrweb to just the record part, but
287
+ // keep backwards compatibility if someone hasn't upgraded PostHog
288
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
289
+ // @ts-ignore
290
+ this.rrwebRecord = window.rrweb ? window.rrweb.record : window.rrwebRecord;
291
+ // only allows user to set our 'allowlisted' options
292
+ var userSessionRecordingOptions = this.instance.get_config('session_recording');
293
+ try {
294
+ for (var _c = __values(Object.entries(userSessionRecordingOptions || {})), _d = _c.next(); !_d.done; _d = _c.next()) {
295
+ var _e = __read(_d.value, 2), key = _e[0], value = _e[1];
296
+ if (key in sessionRecordingOptions) {
297
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
298
+ // @ts-ignore
299
+ sessionRecordingOptions[key] = value;
300
+ }
301
+ }
302
+ }
303
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
304
+ finally {
305
+ try {
306
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
307
+ }
308
+ finally { if (e_1) throw e_1.error; }
309
+ }
310
+ if (!this.rrwebRecord) {
311
+ logger.error('onScriptLoaded was called but rrwebRecord is not available. This indicates something has gone wrong.');
312
+ return;
313
+ }
314
+ this.mutationRateLimiter =
315
+ (_b = this.mutationRateLimiter) !== null && _b !== void 0 ? _b : new MutationRateLimiter(this.rrwebRecord, {
316
+ onBlockedNode: function (id, node) {
317
+ var message = "Too many mutations on node '".concat(id, "'. Rate limiting. This could be due to SVG animations or something similar");
318
+ logger.log(message, {
319
+ node: node,
320
+ });
321
+ _this.log('[PostHog Recorder] ' + message, 'warn');
322
+ },
323
+ });
324
+ this.stopRrweb = this.rrwebRecord(__assign({ emit: function (event) {
325
+ _this.onRRwebEmit(event);
326
+ }, plugins: window.rrwebConsoleRecord && this.isConsoleLogCaptureEnabled()
327
+ ? [window.rrwebConsoleRecord.getRecordConsolePlugin()]
328
+ : [] }, sessionRecordingOptions));
329
+ // :TRICKY: rrweb does not capture navigation within SPA-s, so hook into our $pageview events to get access to all events.
330
+ // Dropping the initial event is fine (it's always captured by rrweb).
331
+ this.instance._addCaptureHook(function (eventName) {
332
+ var _a;
333
+ // If anything could go wrong here it has the potential to block the main loop so we catch all errors.
334
+ try {
335
+ if (eventName === '$pageview') {
336
+ (_a = _this.rrwebRecord) === null || _a === void 0 ? void 0 : _a.addCustomEvent('$pageview', { href: window.location.href });
337
+ }
338
+ }
339
+ catch (e) {
340
+ logger.error('Could not add $pageview to rrweb session', e);
341
+ }
342
+ });
343
+ // We reset the last activity timestamp, resetting the idle timer
344
+ this.lastActivityTimestamp = Date.now();
345
+ this.isIdle = false;
346
+ };
347
+ SessionRecording.prototype.onRRwebEmit = function (rawEvent) {
348
+ if (!rawEvent || typeof rawEvent !== 'object') {
349
+ return;
350
+ }
351
+ var throttledEvent = this.mutationRateLimiter
352
+ ? this.mutationRateLimiter.throttleMutations(rawEvent)
353
+ : rawEvent;
354
+ if (!throttledEvent) {
355
+ return;
356
+ }
357
+ var _a = ensureMaxMessageSize(truncateLargeConsoleLogs(throttledEvent)), event = _a.event, size = _a.size;
358
+ this._updateWindowAndSessionIds(event);
359
+ if (this.isIdle) {
360
+ // When in an idle state we keep recording, but don't capture the events
361
+ return;
362
+ }
363
+ var properties = {
364
+ $snapshot_bytes: size,
365
+ $snapshot_data: event,
366
+ $session_id: this.sessionId,
367
+ $window_id: this.windowId,
368
+ };
369
+ if (this.emit) {
370
+ this._captureSnapshotBuffered(properties);
371
+ }
372
+ else {
373
+ this.snapshots.push(properties);
374
+ }
375
+ };
376
+ SessionRecording.prototype._flushBuffer = function () {
377
+ if (this.flushBufferTimer) {
378
+ clearTimeout(this.flushBufferTimer);
379
+ this.flushBufferTimer = undefined;
380
+ }
381
+ if (this.buffer && this.buffer.data.length !== 0) {
382
+ this._captureSnapshot({
383
+ $snapshot_bytes: this.buffer.size,
384
+ $snapshot_data: this.buffer.data,
385
+ $session_id: this.buffer.sessionId,
386
+ $window_id: this.buffer.windowId,
387
+ });
388
+ }
389
+ this.buffer = undefined;
390
+ return {
391
+ size: 0,
392
+ data: [],
393
+ sessionId: this.sessionId,
394
+ windowId: this.windowId,
395
+ };
396
+ };
397
+ SessionRecording.prototype._captureSnapshotBuffered = function (properties) {
398
+ var _this = this;
399
+ var _a;
400
+ var additionalBytes = 2 + (((_a = this.buffer) === null || _a === void 0 ? void 0 : _a.data.length) || 0); // 2 bytes for the array brackets and 1 byte for each comma
401
+ if (!this.buffer ||
402
+ this.buffer.size + properties.$snapshot_bytes + additionalBytes > RECORDING_MAX_EVENT_SIZE ||
403
+ this.buffer.sessionId !== this.sessionId) {
404
+ this.buffer = this._flushBuffer();
405
+ }
406
+ this.buffer.size += properties.$snapshot_bytes;
407
+ this.buffer.data.push(properties.$snapshot_data);
408
+ if (!this.flushBufferTimer) {
409
+ this.flushBufferTimer = setTimeout(function () {
410
+ _this._flushBuffer();
411
+ }, RECORDING_BUFFER_TIMEOUT);
412
+ }
413
+ };
414
+ SessionRecording.prototype._captureSnapshot = function (properties) {
415
+ // :TRICKY: Make sure we batch these requests, use a custom endpoint and don't truncate the strings.
416
+ this.instance.capture('$snapshot', properties, {
417
+ transport: 'XHR',
418
+ method: 'POST',
419
+ endpoint: this.endpoint,
420
+ _noTruncate: true,
421
+ _batchKey: SESSION_RECORDING_BATCH_KEY,
422
+ _metrics: {
423
+ rrweb_full_snapshot: properties.$snapshot_data.type === FULL_SNAPSHOT_EVENT_TYPE,
424
+ },
425
+ });
426
+ };
427
+ return SessionRecording;
428
+ }());
429
+ export { SessionRecording };
430
+ //# sourceMappingURL=sessionrecording.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sessionrecording.js","sourceRoot":"","sources":["../../../src/extensions/sessionrecording.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EACH,yCAAyC,EACzC,qCAAqC,EACrC,8CAA8C,GACjD,MAAM,cAAc,CAAA;AACrB,OAAO,EACH,oBAAoB,EACpB,wBAAwB,EACxB,+BAA+B,EAC/B,eAAe,EACf,mBAAmB,EAGnB,wBAAwB,GAC3B,MAAM,0BAA0B,CAAA;AAIjC,OAAO,MAAM,MAAM,WAAW,CAAA;AAC9B,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAEzD,IAAM,aAAa,GAAG,KAAK,CAAA;AAE3B,MAAM,CAAC,IAAM,kCAAkC,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAA,CAAC,YAAY;AAC5E,MAAM,CAAC,IAAM,wBAAwB,GA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ING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE,\n} from '../constants'\nimport {\n ensureMaxMessageSize,\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, Properties } from '../types'\nimport type { eventWithTime, listenerHandler } from '@rrweb/types'\nimport Config from '../config'\nimport { logger, loadScript, _timestamp } from '../utils'\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 = 'sessionRecording'\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\nexport class SessionRecording {\n private instance: PostHog\n private emit: boolean\n private endpoint: string\n private windowId: string | null\n private sessionId: string | null\n private lastActivityTimestamp: number = Date.now()\n private flushBufferTimer?: any\n private buffer?: {\n size: number\n data: any[]\n sessionId: string | null\n windowId: string | null\n }\n private mutationRateLimiter?: MutationRateLimiter\n\n captureStarted: boolean\n snapshots: any[]\n stopRrweb: listenerHandler | undefined\n receivedDecide: boolean\n rrwebRecord: rrwebRecord | undefined\n recorderVersion?: string\n isIdle = false\n\n constructor(instance: PostHog) {\n this.instance = instance\n this.captureStarted = false\n this.snapshots = []\n this.emit = false // Controls whether data is sent to the server or not\n this.endpoint = BASE_ENDPOINT\n this.stopRrweb = undefined\n this.windowId = null\n this.sessionId = null\n this.receivedDecide = false\n\n window.addEventListener('beforeunload', () => {\n this._flushBuffer()\n })\n }\n\n startRecordingIfEnabled() {\n if (this.isRecordingEnabled()) {\n this.startCaptureAndTrySendingQueuedSnapshots()\n } else {\n this.stopRecording()\n }\n }\n\n started() {\n return this.captureStarted\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 isRecordingEnabled() {\n const enabled_server_side = !!this.instance.get_property(SESSION_RECORDING_ENABLED_SERVER_SIDE)\n const enabled_client_side = !this.instance.get_config('disable_session_recording')\n return enabled_server_side && enabled_client_side\n }\n\n isConsoleLogCaptureEnabled() {\n const enabled_server_side = !!this.instance.get_property(CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE)\n const enabled_client_side = this.instance.get_config('enable_recording_console_log')\n return enabled_client_side ?? enabled_server_side\n }\n\n getRecordingVersion() {\n const recordingVersion_server_side = this.instance.get_property(SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE)\n const recordingVersion_client_side = this.instance.get_config('session_recording')?.recorderVersion\n return recordingVersion_client_side || recordingVersion_server_side || 'v1'\n }\n\n afterDecideResponse(response: DecideResponse) {\n this.receivedDecide = true\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 if (response.sessionRecording?.endpoint) {\n this.endpoint = response.sessionRecording?.endpoint\n }\n\n if (response.sessionRecording?.recorderVersion) {\n this.recorderVersion = response.sessionRecording.recorderVersion\n }\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 thats what rrweb expects\n payload: [JSON.stringify(message)],\n },\n },\n timestamp: _timestamp(),\n })\n }\n\n private startCaptureAndTrySendingQueuedSnapshots() {\n // Only submit data after we've received a decide response to account for\n // changing endpoints and the feature being disabled on the server side.\n if (this.receivedDecide) {\n this.emit = true\n this.snapshots.forEach((properties) => this._captureSnapshotBuffered(properties))\n }\n this._startCapture()\n }\n\n private _startCapture() {\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 if (typeof Object.assign === 'undefined') {\n return\n }\n\n // We do not switch recorder versions midway through a recording.\n if (this.captureStarted || this.instance.get_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.instance.sessionManager.checkAndGetSessionAndWindowId()\n\n const recorderJS = this.getRecordingVersion() === '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.getRecordingVersion()) {\n loadScript(\n this.instance.get_config('api_host') + `/static/${recorderJS}?v=${Config.LIB_VERSION}`,\n (err) => {\n if (err) {\n return logger.error(`Could not load ${recorderJS}`, err)\n }\n\n this._onScriptLoaded()\n }\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 ingored 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.instance.sessionManager.checkAndGetSessionAndWindowId(\n !isUserInteraction,\n event.timestamp\n )\n\n if (\n [FULL_SNAPSHOT_EVENT_TYPE, META_EVENT_TYPE].indexOf(event.type) === -1 &&\n (this.windowId !== windowId || this.sessionId !== sessionId)\n ) {\n this._tryTakeFullSnapshot()\n }\n this.windowId = windowId\n this.sessionId = sessionId\n }\n\n private _tryTakeFullSnapshot(): boolean {\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 'allowlisted' options\n const userSessionRecordingOptions = this.instance.get_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.log(message, {\n node: node,\n })\n\n this.log('[PostHog Recorder] ' + message, 'warn')\n },\n })\n\n this.stopRrweb = this.rrwebRecord({\n emit: (event) => {\n this.onRRwebEmit(event)\n },\n plugins:\n (window as any).rrwebConsoleRecord && this.isConsoleLogCaptureEnabled()\n ? [(window as any).rrwebConsoleRecord.getRecordConsolePlugin()]\n : [],\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 so we catch all errors.\n try {\n if (eventName === '$pageview') {\n this.rrwebRecord?.addCustomEvent('$pageview', { href: window.location.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 || typeof rawEvent !== 'object') {\n return\n }\n\n const throttledEvent = this.mutationRateLimiter\n ? this.mutationRateLimiter.throttleMutations(rawEvent)\n : rawEvent\n\n if (!throttledEvent) {\n return\n }\n\n const { event, size } = ensureMaxMessageSize(truncateLargeConsoleLogs(throttledEvent))\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.emit) {\n this._captureSnapshotBuffered(properties)\n } else {\n this.snapshots.push(properties)\n }\n }\n\n private _flushBuffer() {\n if (this.flushBufferTimer) {\n clearTimeout(this.flushBufferTimer)\n this.flushBufferTimer = undefined\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\n this.buffer = undefined\n\n return {\n size: 0,\n data: [],\n sessionId: this.sessionId,\n windowId: this.windowId,\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.sessionId\n ) {\n this.buffer = this._flushBuffer()\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"]}
@@ -0,0 +1,18 @@
1
+ import { PostHog } from '../posthog-core';
2
+ import { DecideResponse, ToolbarParams } from '../types';
3
+ export declare class Toolbar {
4
+ instance: PostHog;
5
+ constructor(instance: PostHog);
6
+ afterDecideResponse(response: DecideResponse): void;
7
+ /**
8
+ * To load the toolbar, we need an access token and other state. That state comes from one of three places:
9
+ * 1. In the URL hash params
10
+ * 2. From session storage under the key `toolbarParams` if the toolbar was initialized on a previous page
11
+ */
12
+ maybeLoadToolbar(location?: Location, localStorage?: Storage | undefined, history?: History): boolean;
13
+ loadToolbar(params?: ToolbarParams): boolean;
14
+ /** @deprecated Use "loadToolbar" instead. */
15
+ _loadEditor(params: ToolbarParams): boolean;
16
+ /** @deprecated Use "maybeLoadToolbar" instead. */
17
+ maybeLoadEditor(location?: Location, localStorage?: Storage | undefined, history?: History): boolean;
18
+ }