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