@sentry/replay 7.30.0 → 7.31.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 (138) hide show
  1. package/README.md +46 -34
  2. package/cjs/constants.js +5 -0
  3. package/cjs/constants.js.map +1 -1
  4. package/cjs/coreHandlers/breadcrumbHandler.js.map +1 -1
  5. package/cjs/coreHandlers/handleDom.js.map +1 -1
  6. package/cjs/coreHandlers/handleGlobalEvent.js +13 -11
  7. package/cjs/coreHandlers/handleGlobalEvent.js.map +1 -1
  8. package/cjs/coreHandlers/handleScope.js.map +1 -1
  9. package/cjs/coreHandlers/handleXhr.js +6 -6
  10. package/cjs/coreHandlers/handleXhr.js.map +1 -1
  11. package/cjs/eventBuffer.js +48 -19
  12. package/cjs/eventBuffer.js.map +1 -1
  13. package/cjs/integration.js +19 -19
  14. package/cjs/integration.js.map +1 -1
  15. package/cjs/replay.js +225 -370
  16. package/cjs/replay.js.map +1 -1
  17. package/cjs/util/addEvent.js +10 -10
  18. package/cjs/util/addEvent.js.map +1 -1
  19. package/cjs/util/addMemoryEntry.js +8 -5
  20. package/cjs/util/addMemoryEntry.js.map +1 -1
  21. package/cjs/{createPerformanceEntry.js → util/createPerformanceEntries.js} +14 -8
  22. package/cjs/util/createPerformanceEntries.js.map +1 -0
  23. package/cjs/util/createPerformanceSpans.js +5 -2
  24. package/cjs/util/createPerformanceSpans.js.map +1 -1
  25. package/cjs/util/createReplayEnvelope.js +5 -1
  26. package/cjs/util/createReplayEnvelope.js.map +1 -1
  27. package/cjs/util/isRrwebError.js +3 -7
  28. package/cjs/util/isRrwebError.js.map +1 -1
  29. package/cjs/util/isSessionExpired.js +1 -5
  30. package/cjs/util/isSessionExpired.js.map +1 -1
  31. package/cjs/util/monkeyPatchRecordDroppedEvent.js.map +1 -1
  32. package/cjs/util/{createRecordingData.js → prepareRecordingData.js} +9 -9
  33. package/cjs/util/prepareRecordingData.js.map +1 -0
  34. package/cjs/util/prepareReplayEvent.js +1 -1
  35. package/cjs/util/prepareReplayEvent.js.map +1 -1
  36. package/cjs/util/sendReplay.js +64 -0
  37. package/cjs/util/sendReplay.js.map +1 -0
  38. package/cjs/util/sendReplayRequest.js +157 -0
  39. package/cjs/util/sendReplayRequest.js.map +1 -0
  40. package/cjs/util/shouldFilterRequest.js +3 -6
  41. package/cjs/util/shouldFilterRequest.js.map +1 -1
  42. package/cjs/worker/worker.js +1 -1
  43. package/cjs/worker/worker.js.map +1 -1
  44. package/esm/constants.js +4 -1
  45. package/esm/constants.js.map +1 -1
  46. package/esm/coreHandlers/breadcrumbHandler.js.map +1 -1
  47. package/esm/coreHandlers/handleDom.js.map +1 -1
  48. package/esm/coreHandlers/handleGlobalEvent.js +13 -8
  49. package/esm/coreHandlers/handleGlobalEvent.js.map +1 -1
  50. package/esm/coreHandlers/handleScope.js.map +1 -1
  51. package/esm/coreHandlers/handleXhr.js +6 -3
  52. package/esm/coreHandlers/handleXhr.js.map +1 -1
  53. package/esm/eventBuffer.js +48 -16
  54. package/esm/eventBuffer.js.map +1 -1
  55. package/esm/integration.js +19 -19
  56. package/esm/integration.js.map +1 -1
  57. package/esm/replay.js +228 -370
  58. package/esm/replay.js.map +1 -1
  59. package/esm/util/addEvent.js +10 -7
  60. package/esm/util/addEvent.js.map +1 -1
  61. package/esm/util/addMemoryEntry.js +8 -5
  62. package/esm/util/addMemoryEntry.js.map +1 -1
  63. package/esm/{createPerformanceEntry.js → util/createPerformanceEntries.js} +14 -8
  64. package/esm/util/createPerformanceEntries.js.map +1 -0
  65. package/esm/util/createPerformanceSpans.js +5 -2
  66. package/esm/util/createPerformanceSpans.js.map +1 -1
  67. package/esm/util/createReplayEnvelope.js +5 -1
  68. package/esm/util/createReplayEnvelope.js.map +1 -1
  69. package/esm/util/isRrwebError.js +3 -5
  70. package/esm/util/isRrwebError.js.map +1 -1
  71. package/esm/util/isSessionExpired.js +1 -2
  72. package/esm/util/isSessionExpired.js.map +1 -1
  73. package/esm/util/monkeyPatchRecordDroppedEvent.js.map +1 -1
  74. package/esm/util/{createRecordingData.js → prepareRecordingData.js} +9 -9
  75. package/esm/util/prepareRecordingData.js.map +1 -0
  76. package/esm/util/prepareReplayEvent.js +1 -1
  77. package/esm/util/prepareReplayEvent.js.map +1 -1
  78. package/esm/util/sendReplay.js +62 -0
  79. package/esm/util/sendReplay.js.map +1 -0
  80. package/esm/util/sendReplayRequest.js +153 -0
  81. package/esm/util/sendReplayRequest.js.map +1 -0
  82. package/esm/util/shouldFilterRequest.js +3 -3
  83. package/esm/util/shouldFilterRequest.js.map +1 -1
  84. package/esm/worker/worker.js +1 -1
  85. package/esm/worker/worker.js.map +1 -1
  86. package/package.json +4 -7
  87. package/types/constants.d.ts +2 -0
  88. package/types/constants.d.ts.map +1 -1
  89. package/types/coreHandlers/breadcrumbHandler.d.ts +1 -1
  90. package/types/coreHandlers/breadcrumbHandler.d.ts.map +1 -1
  91. package/types/coreHandlers/handleDom.d.ts +1 -1
  92. package/types/coreHandlers/handleDom.d.ts.map +1 -1
  93. package/types/coreHandlers/handleGlobalEvent.d.ts +1 -1
  94. package/types/coreHandlers/handleGlobalEvent.d.ts.map +1 -1
  95. package/types/coreHandlers/handleScope.d.ts +1 -1
  96. package/types/coreHandlers/handleScope.d.ts.map +1 -1
  97. package/types/coreHandlers/handleXhr.d.ts.map +1 -1
  98. package/types/eventBuffer.d.ts +18 -6
  99. package/types/eventBuffer.d.ts.map +1 -1
  100. package/types/integration.d.ts +5 -5
  101. package/types/integration.d.ts.map +1 -1
  102. package/types/replay.d.ts +55 -69
  103. package/types/replay.d.ts.map +1 -1
  104. package/types/types.d.ts +29 -7
  105. package/types/types.d.ts.map +1 -1
  106. package/types/util/addEvent.d.ts +2 -2
  107. package/types/util/addEvent.d.ts.map +1 -1
  108. package/types/util/addMemoryEntry.d.ts +2 -2
  109. package/types/util/addMemoryEntry.d.ts.map +1 -1
  110. package/types/{createPerformanceEntry.d.ts → util/createPerformanceEntries.d.ts} +2 -2
  111. package/types/util/createPerformanceEntries.d.ts.map +1 -0
  112. package/types/util/createPerformanceSpans.d.ts +2 -2
  113. package/types/util/createPerformanceSpans.d.ts.map +1 -1
  114. package/types/util/createReplayEnvelope.d.ts +1 -1
  115. package/types/util/createReplayEnvelope.d.ts.map +1 -1
  116. package/types/util/isRrwebError.d.ts +1 -1
  117. package/types/util/isRrwebError.d.ts.map +1 -1
  118. package/types/util/prepareRecordingData.d.ts +9 -0
  119. package/types/util/prepareRecordingData.d.ts.map +1 -0
  120. package/types/util/prepareReplayEvent.d.ts +2 -2
  121. package/types/util/prepareReplayEvent.d.ts.map +1 -1
  122. package/types/util/sendReplay.d.ts +9 -0
  123. package/types/util/sendReplay.d.ts.map +1 -0
  124. package/types/util/sendReplayRequest.d.ts +21 -0
  125. package/types/util/sendReplayRequest.d.ts.map +1 -0
  126. package/cjs/createPerformanceEntry.js.map +0 -1
  127. package/cjs/session/deleteSession.js +0 -23
  128. package/cjs/session/deleteSession.js.map +0 -1
  129. package/cjs/util/createRecordingData.js.map +0 -1
  130. package/esm/createPerformanceEntry.js.map +0 -1
  131. package/esm/session/deleteSession.js +0 -21
  132. package/esm/session/deleteSession.js.map +0 -1
  133. package/esm/util/createRecordingData.js.map +0 -1
  134. package/types/createPerformanceEntry.d.ts.map +0 -1
  135. package/types/session/deleteSession.d.ts +0 -5
  136. package/types/session/deleteSession.d.ts.map +0 -1
  137. package/types/util/createRecordingData.d.ts +0 -10
  138. package/types/util/createRecordingData.d.ts.map +0 -1
package/cjs/replay.js CHANGED
@@ -1,7 +1,3 @@
1
- var {
2
- _optionalChain
3
- } = require('@sentry/utils/cjs/buildPolyfills');
4
-
5
1
  Object.defineProperty(exports, '__esModule', { value: true });
6
2
 
7
3
  const core = require('@sentry/core');
@@ -14,34 +10,25 @@ const handleGlobalEvent = require('./coreHandlers/handleGlobalEvent.js');
14
10
  const handleHistory = require('./coreHandlers/handleHistory.js');
15
11
  const handleXhr = require('./coreHandlers/handleXhr.js');
16
12
  const performanceObserver = require('./coreHandlers/performanceObserver.js');
17
- const createPerformanceEntry = require('./createPerformanceEntry.js');
18
13
  const eventBuffer = require('./eventBuffer.js');
19
- const deleteSession = require('./session/deleteSession.js');
20
14
  const getSession = require('./session/getSession.js');
21
15
  const saveSession = require('./session/saveSession.js');
22
16
  const addEvent = require('./util/addEvent.js');
23
17
  const addMemoryEntry = require('./util/addMemoryEntry.js');
24
18
  const createBreadcrumb = require('./util/createBreadcrumb.js');
19
+ const createPerformanceEntries = require('./util/createPerformanceEntries.js');
25
20
  const createPerformanceSpans = require('./util/createPerformanceSpans.js');
26
- const createRecordingData = require('./util/createRecordingData.js');
27
- const createReplayEnvelope = require('./util/createReplayEnvelope.js');
28
21
  const debounce = require('./util/debounce.js');
29
22
  const isExpired = require('./util/isExpired.js');
30
23
  const isSessionExpired = require('./util/isSessionExpired.js');
31
24
  const monkeyPatchRecordDroppedEvent = require('./util/monkeyPatchRecordDroppedEvent.js');
32
- const prepareReplayEvent = require('./util/prepareReplayEvent.js');
25
+ const sendReplay = require('./util/sendReplay.js');
26
+ const sendReplayRequest = require('./util/sendReplayRequest.js');
33
27
  const index = require('./node_modules/rrweb/es/rrweb/packages/rrweb/src/record/index.js');
34
28
  const types = require('./node_modules/rrweb/es/rrweb/packages/rrweb/src/types.js');
35
29
 
36
30
  /* eslint-disable max-lines */ // TODO: We might want to split this file up
37
31
 
38
- /**
39
- * Returns true to return control to calling function, otherwise continue with normal batching
40
- */
41
-
42
- const BASE_RETRY_INTERVAL = 5000;
43
- const MAX_RETRY_COUNT = 3;
44
-
45
32
  /**
46
33
  * The main replay container class, which holds all the state and methods for recording and sending replays.
47
34
  */
@@ -66,40 +53,37 @@ class ReplayContainer {
66
53
 
67
54
  __init4() {this._performanceObserver = null;}
68
55
 
69
- __init5() {this._retryCount = 0;}
70
- __init6() {this._retryInterval = BASE_RETRY_INTERVAL;}
71
-
72
- __init7() {this._flushLock = null;}
56
+ __init5() {this._flushLock = null;}
73
57
 
74
58
  /**
75
59
  * Timestamp of the last user activity. This lives across sessions.
76
60
  */
77
- __init8() {this._lastActivity = new Date().getTime();}
61
+ __init6() {this._lastActivity = new Date().getTime();}
78
62
 
79
63
  /**
80
64
  * Is the integration currently active?
81
65
  */
82
- __init9() {this._isEnabled = false;}
66
+ __init7() {this._isEnabled = false;}
83
67
 
84
68
  /**
85
69
  * Paused is a state where:
86
70
  * - DOM Recording is not listening at all
87
71
  * - Nothing will be added to event buffer (e.g. core SDK events)
88
72
  */
89
- __init10() {this._isPaused = false;}
73
+ __init8() {this._isPaused = false;}
90
74
 
91
75
  /**
92
76
  * Have we attached listeners to the core SDK?
93
77
  * Note we have to track this as there is no way to remove instrumentation handlers.
94
78
  */
95
- __init11() {this._hasInitializedCoreListeners = false;}
79
+ __init9() {this._hasInitializedCoreListeners = false;}
96
80
 
97
81
  /**
98
82
  * Function to stop recording
99
83
  */
100
- __init12() {this._stopRecording = null;}
84
+ __init10() {this._stopRecording = null;}
101
85
 
102
- __init13() {this._context = {
86
+ __init11() {this._context = {
103
87
  errorIds: new Set(),
104
88
  traceIds: new Set(),
105
89
  urls: [],
@@ -108,11 +92,16 @@ class ReplayContainer {
108
92
  initialUrl: '',
109
93
  };}
110
94
 
111
- constructor({ options, recordingOptions }) {;ReplayContainer.prototype.__init.call(this);ReplayContainer.prototype.__init2.call(this);ReplayContainer.prototype.__init3.call(this);ReplayContainer.prototype.__init4.call(this);ReplayContainer.prototype.__init5.call(this);ReplayContainer.prototype.__init6.call(this);ReplayContainer.prototype.__init7.call(this);ReplayContainer.prototype.__init8.call(this);ReplayContainer.prototype.__init9.call(this);ReplayContainer.prototype.__init10.call(this);ReplayContainer.prototype.__init11.call(this);ReplayContainer.prototype.__init12.call(this);ReplayContainer.prototype.__init13.call(this);ReplayContainer.prototype.__init14.call(this);ReplayContainer.prototype.__init15.call(this);ReplayContainer.prototype.__init16.call(this);ReplayContainer.prototype.__init17.call(this);ReplayContainer.prototype.__init18.call(this);ReplayContainer.prototype.__init19.call(this);
95
+ constructor({
96
+ options,
97
+ recordingOptions,
98
+ }
99
+
100
+ ) {;ReplayContainer.prototype.__init.call(this);ReplayContainer.prototype.__init2.call(this);ReplayContainer.prototype.__init3.call(this);ReplayContainer.prototype.__init4.call(this);ReplayContainer.prototype.__init5.call(this);ReplayContainer.prototype.__init6.call(this);ReplayContainer.prototype.__init7.call(this);ReplayContainer.prototype.__init8.call(this);ReplayContainer.prototype.__init9.call(this);ReplayContainer.prototype.__init10.call(this);ReplayContainer.prototype.__init11.call(this);ReplayContainer.prototype.__init12.call(this);ReplayContainer.prototype.__init13.call(this);ReplayContainer.prototype.__init14.call(this);ReplayContainer.prototype.__init15.call(this);ReplayContainer.prototype.__init16.call(this);ReplayContainer.prototype.__init17.call(this);
112
101
  this._recordingOptions = recordingOptions;
113
102
  this._options = options;
114
103
 
115
- this._debouncedFlush = debounce.debounce(() => this.flush(), this._options.flushMinDelay, {
104
+ this._debouncedFlush = debounce.debounce(() => this._flush(), this._options.flushMinDelay, {
116
105
  maxWait: this._options.flushMaxDelay,
117
106
  });
118
107
  }
@@ -143,14 +132,14 @@ class ReplayContainer {
143
132
  * Creates or loads a session, attaches listeners to varying events (DOM,
144
133
  * _performanceObserver, Recording, Sentry SDK, etc)
145
134
  */
146
- start() {
147
- this.setInitialState();
135
+ start() {
136
+ this._setInitialState();
148
137
 
149
- this.loadSession({ expiry: constants.SESSION_IDLE_DURATION });
138
+ this._loadSession({ expiry: constants.SESSION_IDLE_DURATION });
150
139
 
151
140
  // If there is no session, then something bad has happened - can't continue
152
141
  if (!this.session) {
153
- this.handleException(new Error('No session found'));
142
+ this._handleException(new Error('No session found'));
154
143
  return;
155
144
  }
156
145
 
@@ -159,23 +148,21 @@ class ReplayContainer {
159
148
  return;
160
149
  }
161
150
 
162
- // Modify recording options to checkoutEveryNthSecond if
163
- // sampling for error replay. This is because we don't know
164
- // when an error will occur, so we need to keep a buffer of
165
- // replay events.
151
+ // If session is sampled for errors, then we need to set the recordingMode
152
+ // to 'error', which will configure recording with different options.
166
153
  if (this.session.sampled === 'error') {
167
154
  this.recordingMode = 'error';
168
155
  }
169
156
 
170
157
  // setup() is generally called on page load or manually - in both cases we
171
158
  // should treat it as an activity
172
- this.updateSessionActivity();
159
+ this._updateSessionActivity();
173
160
 
174
161
  this.eventBuffer = eventBuffer.createEventBuffer({
175
162
  useCompression: Boolean(this._options.useCompression),
176
163
  });
177
164
 
178
- this.addListeners();
165
+ this._addListeners();
179
166
 
180
167
  // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout
181
168
  this._isEnabled = true;
@@ -188,18 +175,18 @@ class ReplayContainer {
188
175
  *
189
176
  * Note that this will cause a new DOM checkout
190
177
  */
191
- startRecording() {
178
+ startRecording() {
192
179
  try {
193
180
  this._stopRecording = index.default({
194
181
  ...this._recordingOptions,
195
- // When running in error sampling mode, we need to overwrite `checkoutEveryNth`
182
+ // When running in error sampling mode, we need to overwrite `checkoutEveryNms`
196
183
  // Without this, it would record forever, until an error happens, which we don't want
197
184
  // instead, we'll always keep the last 60 seconds of replay before an error happened
198
- ...(this.recordingMode === 'error' && { checkoutEveryNth: 60000 }),
199
- emit: this.handleRecordingEmit,
185
+ ...(this.recordingMode === 'error' && { checkoutEveryNms: 60000 }),
186
+ emit: this._handleRecordingEmit,
200
187
  });
201
188
  } catch (err) {
202
- this.handleException(err);
189
+ this._handleException(err);
203
190
  }
204
191
  }
205
192
 
@@ -220,16 +207,17 @@ class ReplayContainer {
220
207
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK
221
208
  * does not support a teardown
222
209
  */
223
- stop() {
210
+ stop() {
224
211
  try {
225
212
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Replay] Stopping Replays');
226
213
  this._isEnabled = false;
227
- this.removeListeners();
228
- _optionalChain([this, 'access', _8 => _8._stopRecording, 'optionalCall', _9 => _9()]);
229
- _optionalChain([this, 'access', _10 => _10.eventBuffer, 'optionalAccess', _11 => _11.destroy, 'call', _12 => _12()]);
214
+ this._removeListeners();
215
+ this._stopRecording && this._stopRecording();
216
+ this.eventBuffer && this.eventBuffer.destroy();
230
217
  this.eventBuffer = null;
218
+ this._debouncedFlush.cancel();
231
219
  } catch (err) {
232
- this.handleException(err);
220
+ this._handleException(err);
233
221
  }
234
222
  }
235
223
 
@@ -238,7 +226,7 @@ class ReplayContainer {
238
226
  * This differs from stop as this only stops DOM recording, it is
239
227
  * not as thorough of a shutdown as `stop()`.
240
228
  */
241
- pause() {
229
+ pause() {
242
230
  this._isPaused = true;
243
231
  try {
244
232
  if (this._stopRecording) {
@@ -246,7 +234,7 @@ class ReplayContainer {
246
234
  this._stopRecording = undefined;
247
235
  }
248
236
  } catch (err) {
249
- this.handleException(err);
237
+ this._handleException(err);
250
238
  }
251
239
  }
252
240
 
@@ -256,13 +244,85 @@ class ReplayContainer {
256
244
  * Note that calling `startRecording()` here will cause a
257
245
  * new DOM checkout.`
258
246
  */
259
- resume() {
247
+ resume() {
260
248
  this._isPaused = false;
261
249
  this.startRecording();
262
250
  }
263
251
 
252
+ /**
253
+ * We want to batch uploads of replay events. Save events only if
254
+ * `<flushMinDelay>` milliseconds have elapsed since the last event
255
+ * *OR* if `<flushMaxDelay>` milliseconds have elapsed.
256
+ *
257
+ * Accepts a callback to perform side-effects and returns true to stop batch
258
+ * processing and hand back control to caller.
259
+ */
260
+ addUpdate(cb) {
261
+ // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'error'`)
262
+ const cbResult = cb();
263
+
264
+ // If this option is turned on then we will only want to call `flush`
265
+ // explicitly
266
+ if (this.recordingMode === 'error') {
267
+ return;
268
+ }
269
+
270
+ // If callback is true, we do not want to continue with flushing -- the
271
+ // caller will need to handle it.
272
+ if (cbResult === true) {
273
+ return;
274
+ }
275
+
276
+ // addUpdate is called quite frequently - use _debouncedFlush so that it
277
+ // respects the flush delays and does not flush immediately
278
+ this._debouncedFlush();
279
+ }
280
+
281
+ /**
282
+ * Updates the user activity timestamp and resumes recording. This should be
283
+ * called in an event handler for a user action that we consider as the user
284
+ * being "active" (e.g. a mouse click).
285
+ */
286
+ triggerUserActivity() {
287
+ this._updateUserActivity();
288
+
289
+ // This case means that recording was once stopped due to inactivity.
290
+ // Ensure that recording is resumed.
291
+ if (!this._stopRecording) {
292
+ // Create a new session, otherwise when the user action is flushed, it
293
+ // will get rejected due to an expired session.
294
+ this._loadSession({ expiry: constants.SESSION_IDLE_DURATION });
295
+
296
+ // Note: This will cause a new DOM checkout
297
+ this.resume();
298
+ return;
299
+ }
300
+
301
+ // Otherwise... recording was never suspended, continue as normalish
302
+ this._checkAndHandleExpiredSession();
303
+
304
+ this._updateSessionActivity();
305
+ }
306
+
307
+ /**
308
+ *
309
+ * Always flush via `_debouncedFlush` so that we do not have flushes triggered
310
+ * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be
311
+ * cases of mulitple flushes happening closely together.
312
+ */
313
+ flushImmediate() {
314
+ this._debouncedFlush();
315
+ // `.flush` is provided by the debounced function, analogously to lodash.debounce
316
+ return this._debouncedFlush.flush() ;
317
+ }
318
+
319
+ /** Get the current sesion (=replay) ID */
320
+ getSessionId() {
321
+ return this.session && this.session.id;
322
+ }
323
+
264
324
  /** A wrapper to conditionally capture exceptions. */
265
- handleException(error) {
325
+ _handleException(error) {
266
326
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('[Replay]', error);
267
327
 
268
328
  if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && this._options._experiments && this._options._experiments.captureExceptions) {
@@ -270,21 +330,11 @@ class ReplayContainer {
270
330
  }
271
331
  }
272
332
 
273
- /** for tests only */
274
- clearSession() {
275
- try {
276
- deleteSession.deleteSession();
277
- this.session = undefined;
278
- } catch (err) {
279
- this.handleException(err);
280
- }
281
- }
282
-
283
333
  /**
284
334
  * Loads a session from storage, or creates a new one if it does not exist or
285
335
  * is expired.
286
336
  */
287
- loadSession({ expiry }) {
337
+ _loadSession({ expiry }) {
288
338
  const { type, session } = getSession.getSession({
289
339
  expiry,
290
340
  stickySession: Boolean(this._options.stickySession),
@@ -296,11 +346,12 @@ class ReplayContainer {
296
346
  // If session was newly created (i.e. was not loaded from storage), then
297
347
  // enable flag to create the root replay
298
348
  if (type === 'new') {
299
- this.setInitialState();
349
+ this._setInitialState();
300
350
  }
301
351
 
302
- if (session.id !== _optionalChain([this, 'access', _13 => _13.session, 'optionalAccess', _14 => _14.id])) {
303
- session.previousSessionId = _optionalChain([this, 'access', _15 => _15.session, 'optionalAccess', _16 => _16.id]);
352
+ const currentSessionId = this.getSessionId();
353
+ if (session.id !== currentSessionId) {
354
+ session.previousSessionId = currentSessionId;
304
355
  }
305
356
 
306
357
  this.session = session;
@@ -311,14 +362,14 @@ class ReplayContainer {
311
362
  * replay. This is required because otherwise they would be captured at the
312
363
  * first flush.
313
364
  */
314
- setInitialState() {
365
+ _setInitialState() {
315
366
  const urlPath = `${constants.WINDOW.location.pathname}${constants.WINDOW.location.hash}${constants.WINDOW.location.search}`;
316
367
  const url = `${constants.WINDOW.location.origin}${urlPath}`;
317
368
 
318
369
  this.performanceEvents = [];
319
370
 
320
371
  // Reset _context as well
321
- this.clearContext();
372
+ this._clearContext();
322
373
 
323
374
  this._context.initialUrl = url;
324
375
  this._context.initialTimestamp = new Date().getTime();
@@ -328,11 +379,11 @@ class ReplayContainer {
328
379
  /**
329
380
  * Adds listeners to record events for the replay
330
381
  */
331
- addListeners() {
382
+ _addListeners() {
332
383
  try {
333
- constants.WINDOW.document.addEventListener('visibilitychange', this.handleVisibilityChange);
334
- constants.WINDOW.addEventListener('blur', this.handleWindowBlur);
335
- constants.WINDOW.addEventListener('focus', this.handleWindowFocus);
384
+ constants.WINDOW.document.addEventListener('visibilitychange', this._handleVisibilityChange);
385
+ constants.WINDOW.addEventListener('blur', this._handleWindowBlur);
386
+ constants.WINDOW.addEventListener('focus', this._handleWindowFocus);
336
387
 
337
388
  // We need to filter out dropped events captured by `addGlobalEventProcessor(this.handleGlobalEvent)` below
338
389
  monkeyPatchRecordDroppedEvent.overwriteRecordDroppedEvent(this._context.errorIds);
@@ -341,8 +392,10 @@ class ReplayContainer {
341
392
  if (!this._hasInitializedCoreListeners) {
342
393
  // Listeners from core SDK //
343
394
  const scope = core.getCurrentHub().getScope();
344
- _optionalChain([scope, 'optionalAccess', _17 => _17.addScopeListener, 'call', _18 => _18(this.handleCoreBreadcrumbListener('scope'))]);
345
- utils.addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
395
+ if (scope) {
396
+ scope.addScopeListener(this._handleCoreBreadcrumbListener('scope'));
397
+ }
398
+ utils.addInstrumentationHandler('dom', this._handleCoreBreadcrumbListener('dom'));
346
399
  utils.addInstrumentationHandler('fetch', handleFetch.handleFetchSpanListener(this));
347
400
  utils.addInstrumentationHandler('xhr', handleXhr.handleXhrSpanListener(this));
348
401
  utils.addInstrumentationHandler('history', handleHistory.handleHistorySpanListener(this));
@@ -354,7 +407,7 @@ class ReplayContainer {
354
407
  this._hasInitializedCoreListeners = true;
355
408
  }
356
409
  } catch (err) {
357
- this.handleException(err);
410
+ this._handleException(err);
358
411
  }
359
412
 
360
413
  // _performanceObserver //
@@ -366,14 +419,14 @@ class ReplayContainer {
366
419
  }
367
420
 
368
421
  /**
369
- * Cleans up listeners that were created in `addListeners`
422
+ * Cleans up listeners that were created in `_addListeners`
370
423
  */
371
- removeListeners() {
424
+ _removeListeners() {
372
425
  try {
373
- constants.WINDOW.document.removeEventListener('visibilitychange', this.handleVisibilityChange);
426
+ constants.WINDOW.document.removeEventListener('visibilitychange', this._handleVisibilityChange);
374
427
 
375
- constants.WINDOW.removeEventListener('blur', this.handleWindowBlur);
376
- constants.WINDOW.removeEventListener('focus', this.handleWindowFocus);
428
+ constants.WINDOW.removeEventListener('blur', this._handleWindowBlur);
429
+ constants.WINDOW.removeEventListener('focus', this._handleWindowFocus);
377
430
 
378
431
  monkeyPatchRecordDroppedEvent.restoreRecordDroppedEvent();
379
432
 
@@ -382,37 +435,8 @@ class ReplayContainer {
382
435
  this._performanceObserver = null;
383
436
  }
384
437
  } catch (err) {
385
- this.handleException(err);
386
- }
387
- }
388
-
389
- /**
390
- * We want to batch uploads of replay events. Save events only if
391
- * `<flushMinDelay>` milliseconds have elapsed since the last event
392
- * *OR* if `<flushMaxDelay>` milliseconds have elapsed.
393
- *
394
- * Accepts a callback to perform side-effects and returns true to stop batch
395
- * processing and hand back control to caller.
396
- */
397
- addUpdate(cb) {
398
- // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'error'`)
399
- const cbResult = _optionalChain([cb, 'optionalCall', _19 => _19()]);
400
-
401
- // If this option is turned on then we will only want to call `flush`
402
- // explicitly
403
- if (this.recordingMode === 'error') {
404
- return;
405
- }
406
-
407
- // If callback is true, we do not want to continue with flushing -- the
408
- // caller will need to handle it.
409
- if (cbResult === true) {
410
- return;
438
+ this._handleException(err);
411
439
  }
412
-
413
- // addUpdate is called quite frequently - use _debouncedFlush so that it
414
- // respects the flush delays and does not flush immediately
415
- this._debouncedFlush();
416
440
  }
417
441
 
418
442
  /**
@@ -420,12 +444,12 @@ class ReplayContainer {
420
444
  *
421
445
  * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.
422
446
  */
423
- __init14() {this.handleRecordingEmit = (
447
+ __init12() {this._handleRecordingEmit = (
424
448
  event,
425
449
  isCheckout,
426
450
  ) => {
427
451
  // If this is false, it means session is expired, create and a new session and wait for checkout
428
- if (!this.checkAndHandleExpiredSession()) {
452
+ if (!this._checkAndHandleExpiredSession()) {
429
453
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('[Replay] Received replay event after session expired.');
430
454
 
431
455
  return;
@@ -438,12 +462,12 @@ class ReplayContainer {
438
462
  // checkout. This needs to happen before `addEvent()` which updates state
439
463
  // dependent on this reset.
440
464
  if (this.recordingMode === 'error' && event.type === 2) {
441
- this.setInitialState();
465
+ this._setInitialState();
442
466
  }
443
467
 
444
468
  // We need to clear existing events on a checkout, otherwise they are
445
469
  // incremental event updates and should be appended
446
- addEvent.addEvent(this, event, isCheckout);
470
+ void addEvent.addEvent(this, event, isCheckout);
447
471
 
448
472
  // Different behavior for full snapshots (type=2), ignore other event types
449
473
  // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16
@@ -457,7 +481,7 @@ class ReplayContainer {
457
481
  // of the previous session. Do not immediately flush in this case
458
482
  // to avoid capturing only the checkout and instead the replay will
459
483
  // be captured if they perform any follow-up actions.
460
- if (_optionalChain([this, 'access', _20 => _20.session, 'optionalAccess', _21 => _21.previousSessionId])) {
484
+ if (this.session && this.session.previousSessionId) {
461
485
  return true;
462
486
  }
463
487
 
@@ -486,38 +510,38 @@ class ReplayContainer {
486
510
  * be hidden. Likewise, moving a different window to cover the contents of the
487
511
  * page will also trigger a change to a hidden state.
488
512
  */
489
- __init15() {this.handleVisibilityChange = () => {
513
+ __init13() {this._handleVisibilityChange = () => {
490
514
  if (constants.WINDOW.document.visibilityState === 'visible') {
491
- this.doChangeToForegroundTasks();
515
+ this._doChangeToForegroundTasks();
492
516
  } else {
493
- this.doChangeToBackgroundTasks();
517
+ this._doChangeToBackgroundTasks();
494
518
  }
495
519
  };}
496
520
 
497
521
  /**
498
522
  * Handle when page is blurred
499
523
  */
500
- __init16() {this.handleWindowBlur = () => {
524
+ __init14() {this._handleWindowBlur = () => {
501
525
  const breadcrumb = createBreadcrumb.createBreadcrumb({
502
526
  category: 'ui.blur',
503
527
  });
504
528
 
505
529
  // Do not count blur as a user action -- it's part of the process of them
506
530
  // leaving the page
507
- this.doChangeToBackgroundTasks(breadcrumb);
531
+ this._doChangeToBackgroundTasks(breadcrumb);
508
532
  };}
509
533
 
510
534
  /**
511
535
  * Handle when page is focused
512
536
  */
513
- __init17() {this.handleWindowFocus = () => {
537
+ __init15() {this._handleWindowFocus = () => {
514
538
  const breadcrumb = createBreadcrumb.createBreadcrumb({
515
539
  category: 'ui.focus',
516
540
  });
517
541
 
518
542
  // Do not count focus as a user action -- instead wait until they focus and
519
543
  // interactive with page
520
- this.doChangeToForegroundTasks(breadcrumb);
544
+ this._doChangeToForegroundTasks(breadcrumb);
521
545
  };}
522
546
 
523
547
  /**
@@ -525,7 +549,7 @@ class ReplayContainer {
525
549
  *
526
550
  * These events will create breadcrumb-like objects in the recording.
527
551
  */
528
- __init18() {this.handleCoreBreadcrumbListener =
552
+ __init16() {this._handleCoreBreadcrumbListener =
529
553
  (type) =>
530
554
  (handlerData) => {
531
555
  if (!this._isEnabled) {
@@ -545,11 +569,11 @@ class ReplayContainer {
545
569
  if (result.category === 'ui.click') {
546
570
  this.triggerUserActivity();
547
571
  } else {
548
- this.checkAndHandleExpiredSession();
572
+ this._checkAndHandleExpiredSession();
549
573
  }
550
574
 
551
575
  this.addUpdate(() => {
552
- addEvent.addEvent(this, {
576
+ void addEvent.addEvent(this, {
553
577
  type: types.EventType.Custom,
554
578
  // TODO: We were converting from ms to seconds for breadcrumbs, spans,
555
579
  // but maybe we should just keep them as milliseconds
@@ -568,7 +592,7 @@ class ReplayContainer {
568
592
  /**
569
593
  * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)
570
594
  */
571
- doChangeToBackgroundTasks(breadcrumb) {
595
+ _doChangeToBackgroundTasks(breadcrumb) {
572
596
  if (!this.session) {
573
597
  return;
574
598
  }
@@ -576,24 +600,24 @@ class ReplayContainer {
576
600
  const expired = isSessionExpired.isSessionExpired(this.session, constants.VISIBILITY_CHANGE_TIMEOUT);
577
601
 
578
602
  if (breadcrumb && !expired) {
579
- this.createCustomBreadcrumb(breadcrumb);
603
+ this._createCustomBreadcrumb(breadcrumb);
580
604
  }
581
605
 
582
606
  // Send replay when the page/tab becomes hidden. There is no reason to send
583
607
  // replay if it becomes visible, since no actions we care about were done
584
608
  // while it was hidden
585
- this.conditionalFlush();
609
+ this._conditionalFlush();
586
610
  }
587
611
 
588
612
  /**
589
613
  * Tasks to run when we consider a page to be visible (via focus and/or visibility)
590
614
  */
591
- doChangeToForegroundTasks(breadcrumb) {
615
+ _doChangeToForegroundTasks(breadcrumb) {
592
616
  if (!this.session) {
593
617
  return;
594
618
  }
595
619
 
596
- const isSessionActive = this.checkAndHandleExpiredSession({
620
+ const isSessionActive = this._checkAndHandleExpiredSession({
597
621
  expiry: constants.VISIBILITY_CHANGE_TIMEOUT,
598
622
  });
599
623
 
@@ -606,7 +630,7 @@ class ReplayContainer {
606
630
  }
607
631
 
608
632
  if (breadcrumb) {
609
- this.createCustomBreadcrumb(breadcrumb);
633
+ this._createCustomBreadcrumb(breadcrumb);
610
634
  }
611
635
  }
612
636
 
@@ -614,7 +638,7 @@ class ReplayContainer {
614
638
  * Trigger rrweb to take a full snapshot which will cause this plugin to
615
639
  * create a new Replay event.
616
640
  */
617
- triggerFullSnapshot() {
641
+ _triggerFullSnapshot() {
618
642
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Replay] Taking full rrweb snapshot');
619
643
  index.default.takeFullSnapshot(true);
620
644
  }
@@ -622,52 +646,26 @@ class ReplayContainer {
622
646
  /**
623
647
  * Update user activity (across session lifespans)
624
648
  */
625
- updateUserActivity(_lastActivity = new Date().getTime()) {
649
+ _updateUserActivity(_lastActivity = new Date().getTime()) {
626
650
  this._lastActivity = _lastActivity;
627
651
  }
628
652
 
629
653
  /**
630
654
  * Updates the session's last activity timestamp
631
655
  */
632
- updateSessionActivity(_lastActivity = new Date().getTime()) {
656
+ _updateSessionActivity(_lastActivity = new Date().getTime()) {
633
657
  if (this.session) {
634
658
  this.session.lastActivity = _lastActivity;
635
659
  this._maybeSaveSession();
636
660
  }
637
661
  }
638
662
 
639
- /**
640
- * Updates the user activity timestamp and resumes recording. This should be
641
- * called in an event handler for a user action that we consider as the user
642
- * being "active" (e.g. a mouse click).
643
- */
644
- triggerUserActivity() {
645
- this.updateUserActivity();
646
-
647
- // This case means that recording was once stopped due to inactivity.
648
- // Ensure that recording is resumed.
649
- if (!this._stopRecording) {
650
- // Create a new session, otherwise when the user action is flushed, it
651
- // will get rejected due to an expired session.
652
- this.loadSession({ expiry: constants.SESSION_IDLE_DURATION });
653
-
654
- // Note: This will cause a new DOM checkout
655
- this.resume();
656
- return;
657
- }
658
-
659
- // Otherwise... recording was never suspended, continue as normalish
660
- this.checkAndHandleExpiredSession();
661
-
662
- this.updateSessionActivity();
663
- }
664
-
665
663
  /**
666
664
  * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb
667
665
  */
668
- createCustomBreadcrumb(breadcrumb) {
666
+ _createCustomBreadcrumb(breadcrumb) {
669
667
  this.addUpdate(() => {
670
- addEvent.addEvent(this, {
668
+ void addEvent.addEvent(this, {
671
669
  type: types.EventType.Custom,
672
670
  timestamp: breadcrumb.timestamp || 0,
673
671
  data: {
@@ -682,12 +680,12 @@ class ReplayContainer {
682
680
  * Observed performance events are added to `this.performanceEvents`. These
683
681
  * are included in the replay event before it is finished and sent to Sentry.
684
682
  */
685
- addPerformanceEntries() {
683
+ _addPerformanceEntries() {
686
684
  // Copy and reset entries before processing
687
685
  const entries = [...this.performanceEvents];
688
686
  this.performanceEvents = [];
689
687
 
690
- createPerformanceSpans.createPerformanceSpans(this, createPerformanceEntry.createPerformanceEntries(entries));
688
+ return Promise.all(createPerformanceSpans.createPerformanceSpans(this, createPerformanceEntries.createPerformanceEntries(entries)));
691
689
  }
692
690
 
693
691
  /**
@@ -697,8 +695,8 @@ class ReplayContainer {
697
695
  *
698
696
  * Returns true if session is not expired, false otherwise.
699
697
  */
700
- checkAndHandleExpiredSession({ expiry = constants.SESSION_IDLE_DURATION } = {}) {
701
- const oldSessionId = _optionalChain([this, 'access', _22 => _22.session, 'optionalAccess', _23 => _23.id]);
698
+ _checkAndHandleExpiredSession({ expiry = constants.SESSION_IDLE_DURATION } = {}) {
699
+ const oldSessionId = this.getSessionId();
702
700
 
703
701
  // Prevent starting a new session if the last user activity is older than
704
702
  // MAX_SESSION_LIFE. Otherwise non-user activity can trigger a new
@@ -712,17 +710,17 @@ class ReplayContainer {
712
710
 
713
711
  // --- There is recent user activity --- //
714
712
  // This will create a new session if expired, based on expiry length
715
- this.loadSession({ expiry });
713
+ this._loadSession({ expiry });
716
714
 
717
715
  // Session was expired if session ids do not match
718
- const expired = oldSessionId !== _optionalChain([this, 'access', _24 => _24.session, 'optionalAccess', _25 => _25.id]);
716
+ const expired = oldSessionId !== this.getSessionId();
719
717
 
720
718
  if (!expired) {
721
719
  return true;
722
720
  }
723
721
 
724
722
  // Session is expired, trigger a full snapshot (which will create a new session)
725
- this.triggerFullSnapshot();
723
+ this._triggerFullSnapshot();
726
724
 
727
725
  return false;
728
726
  }
@@ -730,7 +728,7 @@ class ReplayContainer {
730
728
  /**
731
729
  * Only flush if `this.recordingMode === 'session'`
732
730
  */
733
- conditionalFlush() {
731
+ _conditionalFlush() {
734
732
  if (this.recordingMode === 'error') {
735
733
  return;
736
734
  }
@@ -741,7 +739,7 @@ class ReplayContainer {
741
739
  /**
742
740
  * Clear _context
743
741
  */
744
- clearContext() {
742
+ _clearContext() {
745
743
  // XXX: `initialTimestamp` and `initialUrl` do not get cleared
746
744
  this._context.errorIds.clear();
747
745
  this._context.traceIds.clear();
@@ -752,7 +750,7 @@ class ReplayContainer {
752
750
  /**
753
751
  * Return and clear _context
754
752
  */
755
- popEventContext() {
753
+ _popEventContext() {
756
754
  if (this._context.earliestEvent && this._context.earliestEvent < this._context.initialTimestamp) {
757
755
  this._context.initialTimestamp = this._context.earliestEvent;
758
756
  }
@@ -765,7 +763,7 @@ class ReplayContainer {
765
763
  urls: this._context.urls,
766
764
  };
767
765
 
768
- this.clearContext();
766
+ this._clearContext();
769
767
 
770
768
  return _context;
771
769
  }
@@ -778,21 +776,27 @@ class ReplayContainer {
778
776
  *
779
777
  * Should never be called directly, only by `flush`
780
778
  */
781
- async runFlush() {
782
- if (!this.session) {
783
- (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('[Replay] No session found to flush.');
779
+ async _runFlush() {
780
+ if (!this.session || !this.eventBuffer) {
781
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('[Replay] No session or eventBuffer found to flush.');
784
782
  return;
785
783
  }
786
784
 
787
- await this.addPerformanceEntries();
785
+ await this._addPerformanceEntries();
788
786
 
789
- if (!_optionalChain([this, 'access', _26 => _26.eventBuffer, 'optionalAccess', _27 => _27.length])) {
787
+ // Check eventBuffer again, as it could have been stopped in the meanwhile
788
+ if (!this.eventBuffer || !this.eventBuffer.pendingLength) {
790
789
  return;
791
790
  }
792
791
 
793
792
  // Only attach memory event if eventBuffer is not empty
794
793
  await addMemoryEntry.addMemoryEntry(this);
795
794
 
795
+ // Check eventBuffer again, as it could have been stopped in the meanwhile
796
+ if (!this.eventBuffer) {
797
+ return;
798
+ }
799
+
796
800
  try {
797
801
  // Note this empties the event buffer regardless of outcome of sending replay
798
802
  const recordingData = await this.eventBuffer.finish();
@@ -800,20 +804,32 @@ class ReplayContainer {
800
804
  // NOTE: Copy values from instance members, as it's possible they could
801
805
  // change before the flush finishes.
802
806
  const replayId = this.session.id;
803
- const eventContext = this.popEventContext();
807
+ const eventContext = this._popEventContext();
804
808
  // Always increment segmentId regardless of outcome of sending replay
805
809
  const segmentId = this.session.segmentId++;
806
810
  this._maybeSaveSession();
807
811
 
808
- await this.sendReplay({
812
+ await sendReplay.sendReplay({
809
813
  replayId,
810
- events: recordingData,
814
+ recordingData,
811
815
  segmentId,
812
816
  includeReplayStartTimestamp: segmentId === 0,
813
817
  eventContext,
818
+ session: this.session,
819
+ options: this.getOptions(),
820
+ timestamp: new Date().getTime(),
814
821
  });
815
822
  } catch (err) {
816
- this.handleException(err);
823
+ this._handleException(err);
824
+
825
+ if (err instanceof sendReplayRequest.RateLimitError) {
826
+ this._handleRateLimit(err.rateLimits);
827
+ return;
828
+ }
829
+
830
+ // This means we retried 3 times, and all of them failed
831
+ // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments
832
+ this.stop();
817
833
  }
818
834
  }
819
835
 
@@ -821,36 +837,35 @@ class ReplayContainer {
821
837
  * Flush recording data to Sentry. Creates a lock so that only a single flush
822
838
  * can be active at a time. Do not call this directly.
823
839
  */
824
- __init19() {this.flush = async () => {
840
+ __init17() {this._flush = async () => {
825
841
  if (!this._isEnabled) {
826
- // This is just a precaution, there should be no listeners that would
827
- // cause a flush.
842
+ // This can happen if e.g. the replay was stopped because of exceeding the retry limit
828
843
  return;
829
844
  }
830
845
 
831
- if (!this.checkAndHandleExpiredSession()) {
846
+ if (!this._checkAndHandleExpiredSession()) {
832
847
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('[Replay] Attempting to finish replay event after session expired.');
833
848
  return;
834
849
  }
835
850
 
836
- if (!_optionalChain([this, 'access', _28 => _28.session, 'optionalAccess', _29 => _29.id])) {
851
+ if (!this.session) {
837
852
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('[Replay] No session found to flush.');
838
853
  return;
839
854
  }
840
855
 
841
856
  // A flush is about to happen, cancel any queued flushes
842
- _optionalChain([this, 'access', _30 => _30._debouncedFlush, 'optionalAccess', _31 => _31.cancel, 'call', _32 => _32()]);
857
+ this._debouncedFlush.cancel();
843
858
 
844
- // this._flushLock acts as a lock so that future calls to `flush()`
859
+ // this._flushLock acts as a lock so that future calls to `_flush()`
845
860
  // will be blocked until this promise resolves
846
861
  if (!this._flushLock) {
847
- this._flushLock = this.runFlush();
862
+ this._flushLock = this._runFlush();
848
863
  await this._flushLock;
849
864
  this._flushLock = null;
850
865
  return;
851
866
  }
852
867
 
853
- // Wait for previous flush to finish, then call the debounced `flush()`.
868
+ // Wait for previous flush to finish, then call the debounced `_flush()`.
854
869
  // It's possible there are other flush requests queued and waiting for it
855
870
  // to resolve. We want to reduce all outstanding requests (as well as any
856
871
  // new flush requests that occur within a second of the locked flush
@@ -865,195 +880,35 @@ class ReplayContainer {
865
880
  }
866
881
  };}
867
882
 
868
- /**
869
- *
870
- * Always flush via `_debouncedFlush` so that we do not have flushes triggered
871
- * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be
872
- * cases of mulitple flushes happening closely together.
873
- */
874
- flushImmediate() {
875
- this._debouncedFlush();
876
- // `.flush` is provided by the debounced function, analogously to lodash.debounce
877
- return this._debouncedFlush.flush() ;
878
- }
879
-
880
- /**
881
- * Send replay attachment using `fetch()`
882
- */
883
- async sendReplayRequest({
884
- events,
885
- replayId,
886
- segmentId: segment_id,
887
- includeReplayStartTimestamp,
888
- eventContext,
889
- }) {
890
- const recordingData = createRecordingData.createRecordingData({
891
- events,
892
- headers: {
893
- segment_id,
894
- },
895
- });
896
-
897
- const { urls, errorIds, traceIds, initialTimestamp } = eventContext;
898
-
899
- const currentTimestamp = new Date().getTime();
900
-
901
- const hub = core.getCurrentHub();
902
- const client = hub.getClient();
903
- const scope = hub.getScope();
904
- const transport = client && client.getTransport();
905
- const dsn = _optionalChain([client, 'optionalAccess', _33 => _33.getDsn, 'call', _34 => _34()]);
906
-
907
- if (!client || !scope || !transport || !dsn || !this.session || !this.session.sampled) {
908
- return;
909
- }
910
-
911
- const baseEvent = {
912
- // @ts-ignore private api
913
- type: constants.REPLAY_EVENT_NAME,
914
- ...(includeReplayStartTimestamp ? { replay_start_timestamp: initialTimestamp / 1000 } : {}),
915
- timestamp: currentTimestamp / 1000,
916
- error_ids: errorIds,
917
- trace_ids: traceIds,
918
- urls,
919
- replay_id: replayId,
920
- segment_id,
921
- replay_type: this.session.sampled,
922
- };
923
-
924
- const replayEvent = await prepareReplayEvent.prepareReplayEvent({ scope, client, replayId, event: baseEvent });
925
-
926
- if (!replayEvent) {
927
- // Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions
928
- client.recordDroppedEvent('event_processor', 'replay_event', baseEvent);
929
- (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('An event processor returned `null`, will not send event.');
930
- return;
931
- }
932
-
933
- replayEvent.tags = {
934
- ...replayEvent.tags,
935
- sessionSampleRate: this._options.sessionSampleRate,
936
- errorSampleRate: this._options.errorSampleRate,
937
- };
938
-
939
- /*
940
- For reference, the fully built event looks something like this:
941
- {
942
- "type": "replay_event",
943
- "timestamp": 1670837008.634,
944
- "error_ids": [
945
- "errorId"
946
- ],
947
- "trace_ids": [
948
- "traceId"
949
- ],
950
- "urls": [
951
- "https://example.com"
952
- ],
953
- "replay_id": "eventId",
954
- "segment_id": 3,
955
- "replay_type": "error",
956
- "platform": "javascript",
957
- "event_id": "eventId",
958
- "environment": "production",
959
- "sdk": {
960
- "integrations": [
961
- "BrowserTracing",
962
- "Replay"
963
- ],
964
- "name": "sentry.javascript.browser",
965
- "version": "7.25.0"
966
- },
967
- "sdkProcessingMetadata": {},
968
- "tags": {
969
- "sessionSampleRate": 1,
970
- "errorSampleRate": 0,
971
- }
972
- }
973
- */
974
-
975
- const envelope = createReplayEnvelope.createReplayEnvelope(replayEvent, recordingData, dsn, client.getOptions().tunnel);
976
-
977
- try {
978
- return await transport.send(envelope);
979
- } catch (e) {
980
- throw new Error(constants.UNABLE_TO_SEND_REPLAY);
883
+ /** Save the session, if it is sticky */
884
+ _maybeSaveSession() {
885
+ if (this.session && this._options.stickySession) {
886
+ saveSession.saveSession(this.session);
981
887
  }
982
888
  }
983
889
 
984
890
  /**
985
- * Reset the counter of retries for sending replays.
986
- */
987
- resetRetries() {
988
- this._retryCount = 0;
989
- this._retryInterval = BASE_RETRY_INTERVAL;
990
- }
991
-
992
- /**
993
- * Finalize and send the current replay event to Sentry
891
+ * Pauses the replay and resumes it after the rate-limit duration is over.
994
892
  */
995
- async sendReplay({
996
- replayId,
997
- events,
998
- segmentId,
999
- includeReplayStartTimestamp,
1000
- eventContext,
1001
- }) {
1002
- // short circuit if there's no events to upload (this shouldn't happen as runFlush makes this check)
1003
- if (!events.length) {
893
+ _handleRateLimit(rateLimits) {
894
+ // in case recording is already paused, we don't need to do anything, as we might have already paused because of a
895
+ // rate limit
896
+ if (this.isPaused()) {
1004
897
  return;
1005
898
  }
1006
899
 
1007
- try {
1008
- await this.sendReplayRequest({
1009
- events,
1010
- replayId,
1011
- segmentId,
1012
- includeReplayStartTimestamp,
1013
- eventContext,
1014
- });
1015
- this.resetRetries();
1016
- return true;
1017
- } catch (err) {
1018
- // Capture error for every failed replay
1019
- core.setContext('Replays', {
1020
- _retryCount: this._retryCount,
1021
- });
1022
- this.handleException(err);
1023
-
1024
- // If an error happened here, it's likely that uploading the attachment
1025
- // failed, we'll can retry with the same events payload
1026
- if (this._retryCount >= MAX_RETRY_COUNT) {
1027
- throw new Error(`${constants.UNABLE_TO_SEND_REPLAY} - max retries exceeded`);
1028
- }
900
+ const rateLimitEnd = utils.disabledUntil(rateLimits, 'replay');
901
+ const rateLimitDuration = rateLimitEnd - Date.now();
1029
902
 
1030
- this._retryCount = this._retryCount + 1;
1031
- // will retry in intervals of 5, 10, 30
1032
- this._retryInterval = this._retryCount * this._retryInterval;
1033
-
1034
- return await new Promise((resolve, reject) => {
1035
- setTimeout(async () => {
1036
- try {
1037
- await this.sendReplay({
1038
- replayId,
1039
- events,
1040
- segmentId,
1041
- includeReplayStartTimestamp,
1042
- eventContext,
1043
- });
1044
- resolve(true);
1045
- } catch (err) {
1046
- reject(err);
1047
- }
1048
- }, this._retryInterval);
1049
- });
1050
- }
1051
- }
903
+ if (rateLimitDuration > 0) {
904
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('[Replay]', `Rate limit hit, pausing replay for ${rateLimitDuration}ms`);
905
+ this.pause();
906
+ this._debouncedFlush.cancel();
1052
907
 
1053
- /** Save the session, if it is sticky */
1054
- _maybeSaveSession() {
1055
- if (this.session && this._options.stickySession) {
1056
- saveSession.saveSession(this.session);
908
+ setTimeout(() => {
909
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.info('[Replay]', 'Resuming replay after rate limit');
910
+ this.resume();
911
+ }, rateLimitDuration);
1057
912
  }
1058
913
  }
1059
914
  }