@sentry/replay 7.49.0 → 7.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +19 -6
  2. package/cjs/index.js +541 -209
  3. package/cjs/index.js.map +1 -1
  4. package/esm/index.js +542 -210
  5. package/esm/index.js.map +1 -1
  6. package/package.json +5 -5
  7. package/types/constants.d.ts +4 -2
  8. package/types/constants.d.ts.map +1 -1
  9. package/types/coreHandlers/handleAfterSendEvent.d.ts.map +1 -1
  10. package/types/coreHandlers/handleNetworkBreadcrumbs.d.ts.map +1 -1
  11. package/types/coreHandlers/handleScope.d.ts +2 -0
  12. package/types/coreHandlers/handleScope.d.ts.map +1 -1
  13. package/types/coreHandlers/util/fetchUtils.d.ts.map +1 -1
  14. package/types/coreHandlers/util/networkUtils.d.ts +4 -0
  15. package/types/coreHandlers/util/networkUtils.d.ts.map +1 -1
  16. package/types/coreHandlers/util/xhrUtils.d.ts.map +1 -1
  17. package/types/eventBuffer/EventBufferArray.d.ts +5 -1
  18. package/types/eventBuffer/EventBufferArray.d.ts.map +1 -1
  19. package/types/eventBuffer/EventBufferCompressionWorker.d.ts +8 -5
  20. package/types/eventBuffer/EventBufferCompressionWorker.d.ts.map +1 -1
  21. package/types/eventBuffer/EventBufferProxy.d.ts +5 -1
  22. package/types/eventBuffer/EventBufferProxy.d.ts.map +1 -1
  23. package/types/integration.d.ts +21 -14
  24. package/types/integration.d.ts.map +1 -1
  25. package/types/replay.d.ts +35 -12
  26. package/types/replay.d.ts.map +1 -1
  27. package/types/session/Session.d.ts +0 -4
  28. package/types/session/Session.d.ts.map +1 -1
  29. package/types/session/clearSession.d.ts +6 -0
  30. package/types/session/clearSession.d.ts.map +1 -0
  31. package/types/session/createSession.d.ts +6 -2
  32. package/types/session/createSession.d.ts.map +1 -1
  33. package/types/session/getSession.d.ts +1 -1
  34. package/types/session/getSession.d.ts.map +1 -1
  35. package/types/types.d.ts +68 -45
  36. package/types/types.d.ts.map +1 -1
  37. package/types/util/addEvent.d.ts.map +1 -1
  38. package/types/util/addGlobalListeners.d.ts.map +1 -1
  39. package/types/util/timestampToMs.d.ts +5 -0
  40. package/types/util/timestampToMs.d.ts.map +1 -0
package/cjs/index.js CHANGED
@@ -13,11 +13,14 @@ const REPLAY_SESSION_KEY = 'sentryReplaySession';
13
13
  const REPLAY_EVENT_NAME = 'replay_event';
14
14
  const UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';
15
15
 
16
- // The idle limit for a session
17
- const SESSION_IDLE_DURATION = 300000; // 5 minutes in ms
16
+ // The idle limit for a session after which recording is paused.
17
+ const SESSION_IDLE_PAUSE_DURATION = 300000; // 5 minutes in ms
18
+
19
+ // The idle limit for a session after which the session expires.
20
+ const SESSION_IDLE_EXPIRE_DURATION = 900000; // 15 minutes in ms
18
21
 
19
22
  // The maximum length of a session
20
- const MAX_SESSION_LIFE = 3600000; // 60 minutes
23
+ const MAX_SESSION_LIFE = 3600000; // 60 minutes in ms
21
24
 
22
25
  /** Default flush delays */
23
26
  const DEFAULT_FLUSH_MIN_DELAY = 5000;
@@ -26,7 +29,7 @@ const DEFAULT_FLUSH_MIN_DELAY = 5000;
26
29
  const DEFAULT_FLUSH_MAX_DELAY = 5500;
27
30
 
28
31
  /* How long to wait for error checkouts */
29
- const ERROR_CHECKOUT_TIME = 60000;
32
+ const BUFFER_CHECKOUT_TIME = 60000;
30
33
 
31
34
  const RETRY_BASE_INTERVAL = 5000;
32
35
  const RETRY_MAX_COUNT = 3;
@@ -34,6 +37,9 @@ const RETRY_MAX_COUNT = 3;
34
37
  /* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */
35
38
  const NETWORK_BODY_MAX_SIZE = 150000;
36
39
 
40
+ /* The max size of a single console arg that is captured. Any arg larger than this will be truncated. */
41
+ const CONSOLE_ARG_MAX_SIZE = 5000;
42
+
37
43
  var NodeType$1;
38
44
  (function (NodeType) {
39
45
  NodeType[NodeType["Document"] = 0] = "Document";
@@ -3371,6 +3377,14 @@ function t(t){let e=t.length;for(;--e>=0;)t[e]=0}const e=new Uint8Array([0,0,0,0
3371
3377
 
3372
3378
  function e(){const e=new Blob([r]);return URL.createObjectURL(e)}
3373
3379
 
3380
+ /**
3381
+ * Converts a timestamp to ms, if it was in s, or keeps it as ms.
3382
+ */
3383
+ function timestampToMs(timestamp) {
3384
+ const isMs = timestamp > 9999999999;
3385
+ return isMs ? timestamp : timestamp * 1000;
3386
+ }
3387
+
3374
3388
  /**
3375
3389
  * A basic event buffer that does not do any compression.
3376
3390
  * Used as fallback if the compression worker cannot be loaded or is disabled.
@@ -3393,14 +3407,8 @@ class EventBufferArray {
3393
3407
  }
3394
3408
 
3395
3409
  /** @inheritdoc */
3396
- async addEvent(event, isCheckout) {
3397
- if (isCheckout) {
3398
- this.events = [event];
3399
- return;
3400
- }
3401
-
3410
+ async addEvent(event) {
3402
3411
  this.events.push(event);
3403
- return;
3404
3412
  }
3405
3413
 
3406
3414
  /** @inheritdoc */
@@ -3414,6 +3422,22 @@ class EventBufferArray {
3414
3422
  resolve(JSON.stringify(eventsRet));
3415
3423
  });
3416
3424
  }
3425
+
3426
+ /** @inheritdoc */
3427
+ clear() {
3428
+ this.events = [];
3429
+ }
3430
+
3431
+ /** @inheritdoc */
3432
+ getEarliestTimestamp() {
3433
+ const timestamp = this.events.map(event => event.timestamp).sort()[0];
3434
+
3435
+ if (!timestamp) {
3436
+ return null;
3437
+ }
3438
+
3439
+ return timestampToMs(timestamp);
3440
+ }
3417
3441
  }
3418
3442
 
3419
3443
  /**
@@ -3521,11 +3545,15 @@ class WorkerHandler {
3521
3545
  * Exported only for testing.
3522
3546
  */
3523
3547
  class EventBufferCompressionWorker {
3524
- /** @inheritdoc */
3525
3548
 
3526
3549
  constructor(worker) {
3527
3550
  this._worker = new WorkerHandler(worker);
3528
- this.hasEvents = false;
3551
+ this._earliestTimestamp = null;
3552
+ }
3553
+
3554
+ /** @inheritdoc */
3555
+ get hasEvents() {
3556
+ return !!this._earliestTimestamp;
3529
3557
  }
3530
3558
 
3531
3559
  /**
@@ -3548,13 +3576,10 @@ class EventBufferCompressionWorker {
3548
3576
  *
3549
3577
  * Returns true if event was successfuly received and processed by worker.
3550
3578
  */
3551
- async addEvent(event, isCheckout) {
3552
- this.hasEvents = true;
3553
-
3554
- if (isCheckout) {
3555
- // This event is a checkout, make sure worker buffer is cleared before
3556
- // proceeding.
3557
- await this._clear();
3579
+ addEvent(event) {
3580
+ const timestamp = timestampToMs(event.timestamp);
3581
+ if (!this._earliestTimestamp || timestamp < this._earliestTimestamp) {
3582
+ this._earliestTimestamp = timestamp;
3558
3583
  }
3559
3584
 
3560
3585
  return this._sendEventToWorker(event);
@@ -3567,6 +3592,18 @@ class EventBufferCompressionWorker {
3567
3592
  return this._finishRequest();
3568
3593
  }
3569
3594
 
3595
+ /** @inheritdoc */
3596
+ clear() {
3597
+ this._earliestTimestamp = null;
3598
+ // We do not wait on this, as we assume the order of messages is consistent for the worker
3599
+ void this._worker.postMessage('clear');
3600
+ }
3601
+
3602
+ /** @inheritdoc */
3603
+ getEarliestTimestamp() {
3604
+ return this._earliestTimestamp;
3605
+ }
3606
+
3570
3607
  /**
3571
3608
  * Send the event to the worker.
3572
3609
  */
@@ -3580,15 +3617,10 @@ class EventBufferCompressionWorker {
3580
3617
  async _finishRequest() {
3581
3618
  const response = await this._worker.postMessage('finish');
3582
3619
 
3583
- this.hasEvents = false;
3620
+ this._earliestTimestamp = null;
3584
3621
 
3585
3622
  return response;
3586
3623
  }
3587
-
3588
- /** Clear any pending events from the worker. */
3589
- _clear() {
3590
- return this._worker.postMessage('clear');
3591
- }
3592
3624
  }
3593
3625
 
3594
3626
  /**
@@ -3617,13 +3649,23 @@ class EventBufferProxy {
3617
3649
  this._compression.destroy();
3618
3650
  }
3619
3651
 
3652
+ /** @inheritdoc */
3653
+ clear() {
3654
+ return this._used.clear();
3655
+ }
3656
+
3657
+ /** @inheritdoc */
3658
+ getEarliestTimestamp() {
3659
+ return this._used.getEarliestTimestamp();
3660
+ }
3661
+
3620
3662
  /**
3621
3663
  * Add an event to the event buffer.
3622
3664
  *
3623
3665
  * Returns true if event was successfully added.
3624
3666
  */
3625
- addEvent(event, isCheckout) {
3626
- return this._used.addEvent(event, isCheckout);
3667
+ addEvent(event) {
3668
+ return this._used.addEvent(event);
3627
3669
  }
3628
3670
 
3629
3671
  /** @inheritDoc */
@@ -3698,6 +3740,31 @@ function createEventBuffer({ useCompression }) {
3698
3740
  return new EventBufferArray();
3699
3741
  }
3700
3742
 
3743
+ /**
3744
+ * Removes the session from Session Storage and unsets session in replay instance
3745
+ */
3746
+ function clearSession(replay) {
3747
+ deleteSession();
3748
+ replay.session = undefined;
3749
+ }
3750
+
3751
+ /**
3752
+ * Deletes a session from storage
3753
+ */
3754
+ function deleteSession() {
3755
+ const hasSessionStorage = 'sessionStorage' in WINDOW;
3756
+
3757
+ if (!hasSessionStorage) {
3758
+ return;
3759
+ }
3760
+
3761
+ try {
3762
+ WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY);
3763
+ } catch (e) {
3764
+ // Ignore potential SecurityError exceptions
3765
+ }
3766
+ }
3767
+
3701
3768
  /**
3702
3769
  * Given an initial timestamp and an expiry duration, checks to see if current
3703
3770
  * time should be considered as expired.
@@ -3728,11 +3795,26 @@ function isSessionExpired(session, timeouts, targetTime = +new Date()) {
3728
3795
  // First, check that maximum session length has not been exceeded
3729
3796
  isExpired(session.started, timeouts.maxSessionLife, targetTime) ||
3730
3797
  // check that the idle timeout has not been exceeded (i.e. user has
3731
- // performed an action within the last `idleTimeout` ms)
3732
- isExpired(session.lastActivity, timeouts.sessionIdle, targetTime)
3798
+ // performed an action within the last `sessionIdleExpire` ms)
3799
+ isExpired(session.lastActivity, timeouts.sessionIdleExpire, targetTime)
3733
3800
  );
3734
3801
  }
3735
3802
 
3803
+ /**
3804
+ * Given a sample rate, returns true if replay should be sampled.
3805
+ *
3806
+ * 1.0 = 100% sampling
3807
+ * 0.0 = 0% sampling
3808
+ */
3809
+ function isSampled(sampleRate) {
3810
+ if (sampleRate === undefined) {
3811
+ return false;
3812
+ }
3813
+
3814
+ // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)
3815
+ return Math.random() < sampleRate;
3816
+ }
3817
+
3736
3818
  /**
3737
3819
  * Save a session to session storage.
3738
3820
  */
@@ -3749,21 +3831,6 @@ function saveSession(session) {
3749
3831
  }
3750
3832
  }
3751
3833
 
3752
- /**
3753
- * Given a sample rate, returns true if replay should be sampled.
3754
- *
3755
- * 1.0 = 100% sampling
3756
- * 0.0 = 0% sampling
3757
- */
3758
- function isSampled(sampleRate) {
3759
- if (sampleRate === undefined) {
3760
- return false;
3761
- }
3762
-
3763
- // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)
3764
- return Math.random() < sampleRate;
3765
- }
3766
-
3767
3834
  /**
3768
3835
  * Get a session with defaults & applied sampling.
3769
3836
  */
@@ -3782,14 +3849,15 @@ function makeSession(session) {
3782
3849
  lastActivity,
3783
3850
  segmentId,
3784
3851
  sampled,
3852
+ shouldRefresh: true,
3785
3853
  };
3786
3854
  }
3787
3855
 
3788
3856
  /**
3789
3857
  * Get the sampled status for a session based on sample rates & current sampled status.
3790
3858
  */
3791
- function getSessionSampleType(sessionSampleRate, errorSampleRate) {
3792
- return isSampled(sessionSampleRate) ? 'session' : isSampled(errorSampleRate) ? 'error' : false;
3859
+ function getSessionSampleType(sessionSampleRate, allowBuffering) {
3860
+ return isSampled(sessionSampleRate) ? 'session' : allowBuffering ? 'buffer' : false;
3793
3861
  }
3794
3862
 
3795
3863
  /**
@@ -3797,8 +3865,8 @@ function getSessionSampleType(sessionSampleRate, errorSampleRate) {
3797
3865
  * that all replays will be saved to as attachments. Currently, we only expect
3798
3866
  * one of these Sentry events per "replay session".
3799
3867
  */
3800
- function createSession({ sessionSampleRate, errorSampleRate, stickySession = false }) {
3801
- const sampled = getSessionSampleType(sessionSampleRate, errorSampleRate);
3868
+ function createSession({ sessionSampleRate, allowBuffering, stickySession = false }) {
3869
+ const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);
3802
3870
  const session = makeSession({
3803
3871
  sampled,
3804
3872
  });
@@ -3846,7 +3914,7 @@ function getSession({
3846
3914
  currentSession,
3847
3915
  stickySession,
3848
3916
  sessionSampleRate,
3849
- errorSampleRate,
3917
+ allowBuffering,
3850
3918
  }) {
3851
3919
  // If session exists and is passed, use it instead of always hitting session storage
3852
3920
  const session = currentSession || (stickySession && fetchSession());
@@ -3859,8 +3927,9 @@ function getSession({
3859
3927
 
3860
3928
  if (!isExpired) {
3861
3929
  return { type: 'saved', session };
3862
- } else if (session.sampled === 'error') {
3863
- // Error samples should not be re-created when expired, but instead we stop when the replay is done
3930
+ } else if (!session.shouldRefresh) {
3931
+ // In this case, stop
3932
+ // This is the case if we have an error session that is completed (=triggered an error)
3864
3933
  const discardedSession = makeSession({ sampled: false });
3865
3934
  return { type: 'new', session: discardedSession };
3866
3935
  } else {
@@ -3872,7 +3941,7 @@ function getSession({
3872
3941
  const newSession = createSession({
3873
3942
  stickySession,
3874
3943
  sessionSampleRate,
3875
- errorSampleRate,
3944
+ allowBuffering,
3876
3945
  });
3877
3946
 
3878
3947
  return { type: 'new', session: newSession };
@@ -3897,31 +3966,25 @@ async function addEvent(
3897
3966
  return null;
3898
3967
  }
3899
3968
 
3900
- // TODO: sadness -- we will want to normalize timestamps to be in ms -
3901
- // requires coordination with frontend
3902
- const isMs = event.timestamp > 9999999999;
3903
- const timestampInMs = isMs ? event.timestamp : event.timestamp * 1000;
3969
+ const timestampInMs = timestampToMs(event.timestamp);
3904
3970
 
3905
3971
  // Throw out events that happen more than 5 minutes ago. This can happen if
3906
3972
  // page has been left open and idle for a long period of time and user
3907
3973
  // comes back to trigger a new session. The performance entries rely on
3908
3974
  // `performance.timeOrigin`, which is when the page first opened.
3909
- if (timestampInMs + replay.timeouts.sessionIdle < Date.now()) {
3975
+ if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) {
3910
3976
  return null;
3911
3977
  }
3912
3978
 
3913
- // Only record earliest event if a new session was created, otherwise it
3914
- // shouldn't be relevant
3915
- const earliestEvent = replay.getContext().earliestEvent;
3916
- if (replay.session && replay.session.segmentId === 0 && (!earliestEvent || timestampInMs < earliestEvent)) {
3917
- replay.getContext().earliestEvent = timestampInMs;
3918
- }
3919
-
3920
3979
  try {
3921
- return await replay.eventBuffer.addEvent(event, isCheckout);
3980
+ if (isCheckout) {
3981
+ replay.eventBuffer.clear();
3982
+ }
3983
+
3984
+ return await replay.eventBuffer.addEvent(event);
3922
3985
  } catch (error) {
3923
3986
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error(error);
3924
- replay.stop('addEvent');
3987
+ await replay.stop('addEvent');
3925
3988
 
3926
3989
  const client = core.getCurrentHub().getClient();
3927
3990
 
@@ -3988,23 +4051,17 @@ function handleAfterSendEvent(replay) {
3988
4051
  // Trigger error recording
3989
4052
  // Need to be very careful that this does not cause an infinite loop
3990
4053
  if (
3991
- replay.recordingMode === 'error' &&
4054
+ replay.recordingMode === 'buffer' &&
3992
4055
  event.exception &&
3993
4056
  event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because otherwise we could loop indefinitely with trying to capture replay and failing
3994
4057
  ) {
3995
- setTimeout(async () => {
3996
- // Allow flush to complete before resuming as a session recording, otherwise
3997
- // the checkout from `startRecording` may be included in the payload.
3998
- // Prefer to keep the error replay as a separate (and smaller) segment
3999
- // than the session replay.
4000
- await replay.flushImmediate();
4001
-
4002
- if (replay.stopRecording()) {
4003
- // Reset all "capture on error" configuration before
4004
- // starting a new recording
4005
- replay.recordingMode = 'session';
4006
- replay.startRecording();
4007
- }
4058
+ if (!isSampled(replay.getOptions().errorSampleRate)) {
4059
+ return;
4060
+ }
4061
+
4062
+ setTimeout(() => {
4063
+ // Capture current event buffer as new replay
4064
+ void replay.sendBufferedReplayOrFlush();
4008
4065
  });
4009
4066
  }
4010
4067
  };
@@ -4959,6 +5016,17 @@ function makeNetworkReplayBreadcrumb(
4959
5016
  return result;
4960
5017
  }
4961
5018
 
5019
+ /** Build the request or response part of a replay network breadcrumb that was skipped. */
5020
+ function buildSkippedNetworkRequestOrResponse(bodySize) {
5021
+ return {
5022
+ headers: {},
5023
+ size: bodySize,
5024
+ _meta: {
5025
+ warnings: ['URL_SKIPPED'],
5026
+ },
5027
+ };
5028
+ }
5029
+
4962
5030
  /** Build the request or response part of a replay network breadcrumb. */
4963
5031
  function buildNetworkRequestOrResponse(
4964
5032
  headers,
@@ -5039,8 +5107,8 @@ function normalizeNetworkBody(body)
5039
5107
  };
5040
5108
  } catch (e3) {
5041
5109
  return {
5042
- body,
5043
- warnings: ['INVALID_JSON'],
5110
+ body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,
5111
+ warnings: exceedsSizeLimit ? ['INVALID_JSON', 'TEXT_TRUNCATED'] : ['INVALID_JSON'],
5044
5112
  };
5045
5113
  }
5046
5114
  }
@@ -5059,6 +5127,11 @@ function _strIsProbablyJson(str) {
5059
5127
  return (first === '[' && last === ']') || (first === '{' && last === '}');
5060
5128
  }
5061
5129
 
5130
+ /** Match an URL against a list of strings/Regex. */
5131
+ function urlMatches(url, urls) {
5132
+ return utils.stringMatchesSomePattern(url, urls);
5133
+ }
5134
+
5062
5135
  /**
5063
5136
  * Capture a fetch breadcrumb to a replay.
5064
5137
  * This adds additional data (where approriate).
@@ -5118,33 +5191,37 @@ async function _prepareFetchData(
5118
5191
  const {
5119
5192
  url,
5120
5193
  method,
5121
- status_code: statusCode,
5194
+ status_code: statusCode = 0,
5122
5195
  request_body_size: requestBodySize,
5123
5196
  response_body_size: responseBodySize,
5124
5197
  } = breadcrumb.data;
5125
5198
 
5126
- const request = _getRequestInfo(options, hint.input, requestBodySize);
5127
- const response = await _getResponseInfo(options, hint.response, responseBodySize);
5199
+ const captureDetails = urlMatches(url, options.networkDetailAllowUrls);
5200
+
5201
+ const request = captureDetails
5202
+ ? _getRequestInfo(options, hint.input, requestBodySize)
5203
+ : buildSkippedNetworkRequestOrResponse(requestBodySize);
5204
+ const response = await _getResponseInfo(captureDetails, options, hint.response, responseBodySize);
5128
5205
 
5129
5206
  return {
5130
5207
  startTimestamp,
5131
5208
  endTimestamp,
5132
5209
  url,
5133
5210
  method,
5134
- statusCode: statusCode || 0,
5211
+ statusCode,
5135
5212
  request,
5136
5213
  response,
5137
5214
  };
5138
5215
  }
5139
5216
 
5140
5217
  function _getRequestInfo(
5141
- { captureBodies, requestHeaders },
5218
+ { networkCaptureBodies, networkRequestHeaders },
5142
5219
  input,
5143
5220
  requestBodySize,
5144
5221
  ) {
5145
- const headers = getRequestHeaders(input, requestHeaders);
5222
+ const headers = getRequestHeaders(input, networkRequestHeaders);
5146
5223
 
5147
- if (!captureBodies) {
5224
+ if (!networkCaptureBodies) {
5148
5225
  return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);
5149
5226
  }
5150
5227
 
@@ -5155,19 +5232,24 @@ function _getRequestInfo(
5155
5232
  }
5156
5233
 
5157
5234
  async function _getResponseInfo(
5235
+ captureDetails,
5158
5236
  {
5159
- captureBodies,
5237
+ networkCaptureBodies,
5160
5238
  textEncoder,
5161
- responseHeaders,
5239
+ networkResponseHeaders,
5162
5240
  }
5163
5241
 
5164
5242
  ,
5165
5243
  response,
5166
5244
  responseBodySize,
5167
5245
  ) {
5168
- const headers = getAllHeaders(response.headers, responseHeaders);
5246
+ if (!captureDetails && responseBodySize !== undefined) {
5247
+ return buildSkippedNetworkRequestOrResponse(responseBodySize);
5248
+ }
5249
+
5250
+ const headers = getAllHeaders(response.headers, networkResponseHeaders);
5169
5251
 
5170
- if (!captureBodies && responseBodySize !== undefined) {
5252
+ if (!networkCaptureBodies && responseBodySize !== undefined) {
5171
5253
  return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);
5172
5254
  }
5173
5255
 
@@ -5182,7 +5264,11 @@ async function _getResponseInfo(
5182
5264
  ? getBodySize(bodyText, textEncoder)
5183
5265
  : responseBodySize;
5184
5266
 
5185
- if (captureBodies) {
5267
+ if (!captureDetails) {
5268
+ return buildSkippedNetworkRequestOrResponse(size);
5269
+ }
5270
+
5271
+ if (networkCaptureBodies) {
5186
5272
  return buildNetworkRequestOrResponse(headers, size, bodyText);
5187
5273
  }
5188
5274
 
@@ -5315,28 +5401,44 @@ function _prepareXhrData(
5315
5401
  const {
5316
5402
  url,
5317
5403
  method,
5318
- status_code: statusCode,
5404
+ status_code: statusCode = 0,
5319
5405
  request_body_size: requestBodySize,
5320
5406
  response_body_size: responseBodySize,
5321
5407
  } = breadcrumb.data;
5322
5408
 
5323
- const xhrInfo = xhr[utils.SENTRY_XHR_DATA_KEY];
5324
- const requestHeaders = xhrInfo ? getAllowedHeaders(xhrInfo.request_headers, options.requestHeaders) : {};
5325
- const responseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.responseHeaders);
5326
-
5327
5409
  if (!url) {
5328
5410
  return null;
5329
5411
  }
5330
5412
 
5413
+ if (!urlMatches(url, options.networkDetailAllowUrls)) {
5414
+ const request = buildSkippedNetworkRequestOrResponse(requestBodySize);
5415
+ const response = buildSkippedNetworkRequestOrResponse(responseBodySize);
5416
+ return {
5417
+ startTimestamp,
5418
+ endTimestamp,
5419
+ url,
5420
+ method,
5421
+ statusCode,
5422
+ request,
5423
+ response,
5424
+ };
5425
+ }
5426
+
5427
+ const xhrInfo = xhr[utils.SENTRY_XHR_DATA_KEY];
5428
+ const networkRequestHeaders = xhrInfo
5429
+ ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders)
5430
+ : {};
5431
+ const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.networkResponseHeaders);
5432
+
5331
5433
  const request = buildNetworkRequestOrResponse(
5332
- requestHeaders,
5434
+ networkRequestHeaders,
5333
5435
  requestBodySize,
5334
- options.captureBodies ? getBodyString(input) : undefined,
5436
+ options.networkCaptureBodies ? getBodyString(input) : undefined,
5335
5437
  );
5336
5438
  const response = buildNetworkRequestOrResponse(
5337
- responseHeaders,
5439
+ networkResponseHeaders,
5338
5440
  responseBodySize,
5339
- options.captureBodies ? hint.xhr.responseText : undefined,
5441
+ options.networkCaptureBodies ? hint.xhr.responseText : undefined,
5340
5442
  );
5341
5443
 
5342
5444
  return {
@@ -5344,7 +5446,7 @@ function _prepareXhrData(
5344
5446
  endTimestamp,
5345
5447
  url,
5346
5448
  method,
5347
- statusCode: statusCode || 0,
5449
+ statusCode,
5348
5450
  request,
5349
5451
  response,
5350
5452
  };
@@ -5376,10 +5478,16 @@ function handleNetworkBreadcrumbs(replay) {
5376
5478
  try {
5377
5479
  const textEncoder = new TextEncoder();
5378
5480
 
5481
+ const { networkDetailAllowUrls, networkCaptureBodies, networkRequestHeaders, networkResponseHeaders } =
5482
+ replay.getOptions();
5483
+
5379
5484
  const options = {
5380
5485
  replay,
5381
5486
  textEncoder,
5382
- ...replay.getExperimentalOptions().network,
5487
+ networkDetailAllowUrls,
5488
+ networkCaptureBodies,
5489
+ networkRequestHeaders,
5490
+ networkResponseHeaders,
5383
5491
  };
5384
5492
 
5385
5493
  if (client && client.on) {
@@ -5487,9 +5595,66 @@ function handleScope(scope) {
5487
5595
  return null;
5488
5596
  }
5489
5597
 
5598
+ if (newBreadcrumb.category === 'console') {
5599
+ return normalizeConsoleBreadcrumb(newBreadcrumb);
5600
+ }
5601
+
5490
5602
  return createBreadcrumb(newBreadcrumb);
5491
5603
  }
5492
5604
 
5605
+ /** exported for tests only */
5606
+ function normalizeConsoleBreadcrumb(breadcrumb) {
5607
+ const args = breadcrumb.data && breadcrumb.data.arguments;
5608
+
5609
+ if (!Array.isArray(args) || args.length === 0) {
5610
+ return createBreadcrumb(breadcrumb);
5611
+ }
5612
+
5613
+ let isTruncated = false;
5614
+
5615
+ // Avoid giant args captures
5616
+ const normalizedArgs = args.map(arg => {
5617
+ if (!arg) {
5618
+ return arg;
5619
+ }
5620
+ if (typeof arg === 'string') {
5621
+ if (arg.length > CONSOLE_ARG_MAX_SIZE) {
5622
+ isTruncated = true;
5623
+ return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;
5624
+ }
5625
+
5626
+ return arg;
5627
+ }
5628
+ if (typeof arg === 'object') {
5629
+ try {
5630
+ const normalizedArg = utils.normalize(arg, 7);
5631
+ const stringified = JSON.stringify(normalizedArg);
5632
+ if (stringified.length > CONSOLE_ARG_MAX_SIZE) {
5633
+ const fixedJson = fixJson(stringified.slice(0, CONSOLE_ARG_MAX_SIZE));
5634
+ const json = JSON.parse(fixedJson);
5635
+ // We only set this after JSON.parse() was successfull, so we know we didn't run into `catch`
5636
+ isTruncated = true;
5637
+ return json;
5638
+ }
5639
+ return normalizedArg;
5640
+ } catch (e) {
5641
+ // fall back to default
5642
+ }
5643
+ }
5644
+
5645
+ return arg;
5646
+ });
5647
+
5648
+ return createBreadcrumb({
5649
+ ...breadcrumb,
5650
+ data: {
5651
+ ...breadcrumb.data,
5652
+ arguments: normalizedArgs,
5653
+ ...(isTruncated ? { _meta: { warnings: ['CONSOLE_ARG_TRUNCATED'] } } : {}),
5654
+ },
5655
+ });
5656
+ }
5657
+
5493
5658
  /**
5494
5659
  * Add global listeners that cannot be removed.
5495
5660
  */
@@ -5514,7 +5679,8 @@ function addGlobalListeners(replay) {
5514
5679
  client.on('afterSendEvent', handleAfterSendEvent(replay));
5515
5680
  client.on('createDsc', (dsc) => {
5516
5681
  const replayId = replay.getSessionId();
5517
- if (replayId) {
5682
+ // We do not want to set the DSC when in buffer mode, as that means the replay has not been sent (yet)
5683
+ if (replayId && replay.isEnabled() && replay.recordingMode === 'session') {
5518
5684
  dsc.replay_id = replayId;
5519
5685
  }
5520
5686
  });
@@ -5822,7 +5988,7 @@ function getHandleRecordingEmit(replay) {
5822
5988
  // when an error occurs. Clear any state that happens before this current
5823
5989
  // checkout. This needs to happen before `addEvent()` which updates state
5824
5990
  // dependent on this reset.
5825
- if (replay.recordingMode === 'error' && isCheckout) {
5991
+ if (replay.recordingMode === 'buffer' && isCheckout) {
5826
5992
  replay.setInitialState();
5827
5993
  }
5828
5994
 
@@ -5846,10 +6012,10 @@ function getHandleRecordingEmit(replay) {
5846
6012
  return true;
5847
6013
  }
5848
6014
 
5849
- // See note above re: session start needs to reflect the most recent
5850
- // checkout.
5851
- if (replay.recordingMode === 'error' && replay.session) {
5852
- const { earliestEvent } = replay.getContext();
6015
+ // When in buffer mode, make sure we adjust the session started date to the current earliest event of the buffer
6016
+ // this should usually be the timestamp of the checkout event, but to be safe...
6017
+ if (replay.recordingMode === 'buffer' && replay.session && replay.eventBuffer) {
6018
+ const earliestEvent = replay.eventBuffer.getEarliestTimestamp();
5853
6019
  if (earliestEvent) {
5854
6020
  replay.session.started = earliestEvent;
5855
6021
 
@@ -6197,9 +6363,11 @@ class ReplayContainer {
6197
6363
  __init2() {this.performanceEvents = [];}
6198
6364
 
6199
6365
  /**
6200
- * Recording can happen in one of two modes:
6201
- * * session: Record the whole session, sending it continuously
6202
- * * error: Always keep the last 60s of recording, and when an error occurs, send it immediately
6366
+ * Recording can happen in one of three modes:
6367
+ * - session: Record the whole session, sending it continuously
6368
+ * - buffer: Always keep the last 60s of recording, requires:
6369
+ * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs
6370
+ * - or calling `flush()` to send the replay
6203
6371
  */
6204
6372
  __init3() {this.recordingMode = 'session';}
6205
6373
 
@@ -6208,7 +6376,8 @@ class ReplayContainer {
6208
6376
  * @hidden
6209
6377
  */
6210
6378
  __init4() {this.timeouts = {
6211
- sessionIdle: SESSION_IDLE_DURATION,
6379
+ sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,
6380
+ sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,
6212
6381
  maxSessionLife: MAX_SESSION_LIFE,
6213
6382
  }; }
6214
6383
 
@@ -6252,7 +6421,6 @@ class ReplayContainer {
6252
6421
  errorIds: new Set(),
6253
6422
  traceIds: new Set(),
6254
6423
  urls: [],
6255
- earliestEvent: null,
6256
6424
  initialTimestamp: Date.now(),
6257
6425
  initialUrl: '',
6258
6426
  };}
@@ -6269,8 +6437,6 @@ class ReplayContainer {
6269
6437
  this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {
6270
6438
  maxWait: this._options.flushMaxDelay,
6271
6439
  });
6272
-
6273
- this._experimentalOptions = _getExperimentalOptions(options);
6274
6440
  }
6275
6441
 
6276
6442
  /** Get the event context. */
@@ -6294,58 +6460,102 @@ class ReplayContainer {
6294
6460
  }
6295
6461
 
6296
6462
  /**
6297
- * Get the experimental options.
6298
- * THIS IS INTERNAL AND SUBJECT TO CHANGE!
6299
- * @hidden
6463
+ * Initializes the plugin based on sampling configuration. Should not be
6464
+ * called outside of constructor.
6300
6465
  */
6301
- getExperimentalOptions() {
6302
- return this._experimentalOptions;
6466
+ initializeSampling() {
6467
+ const { errorSampleRate, sessionSampleRate } = this._options;
6468
+
6469
+ // If neither sample rate is > 0, then do nothing - user will need to call one of
6470
+ // `start()` or `startBuffering` themselves.
6471
+ if (errorSampleRate <= 0 && sessionSampleRate <= 0) {
6472
+ return;
6473
+ }
6474
+
6475
+ // Otherwise if there is _any_ sample rate set, try to load an existing
6476
+ // session, or create a new one.
6477
+ const isSessionSampled = this._loadAndCheckSession();
6478
+
6479
+ if (!isSessionSampled) {
6480
+ // This should only occur if `errorSampleRate` is 0 and was unsampled for
6481
+ // session-based replay. In this case there is nothing to do.
6482
+ return;
6483
+ }
6484
+
6485
+ if (!this.session) {
6486
+ // This should not happen, something wrong has occurred
6487
+ this._handleException(new Error('Unable to initialize and create session'));
6488
+ return;
6489
+ }
6490
+
6491
+ if (this.session.sampled && this.session.sampled !== 'session') {
6492
+ // If not sampled as session-based, then recording mode will be `buffer`
6493
+ // Note that we don't explicitly check if `sampled === 'buffer'` because we
6494
+ // could have sessions from Session storage that are still `error` from
6495
+ // prior SDK version.
6496
+ this.recordingMode = 'buffer';
6497
+ }
6498
+
6499
+ this._initializeRecording();
6303
6500
  }
6304
6501
 
6305
6502
  /**
6306
- * Initializes the plugin.
6503
+ * Start a replay regardless of sampling rate. Calling this will always
6504
+ * create a new session. Will throw an error if replay is already in progress.
6307
6505
  *
6308
6506
  * Creates or loads a session, attaches listeners to varying events (DOM,
6309
6507
  * _performanceObserver, Recording, Sentry SDK, etc)
6310
6508
  */
6311
6509
  start() {
6312
- this.setInitialState();
6313
-
6314
- if (!this._loadAndCheckSession()) {
6315
- return;
6510
+ if (this._isEnabled && this.recordingMode === 'session') {
6511
+ throw new Error('Replay recording is already in progress');
6316
6512
  }
6317
6513
 
6318
- // If there is no session, then something bad has happened - can't continue
6319
- if (!this.session) {
6320
- this._handleException(new Error('No session found'));
6321
- return;
6514
+ if (this._isEnabled && this.recordingMode === 'buffer') {
6515
+ throw new Error('Replay buffering is in progress, call `flush()` to save the replay');
6322
6516
  }
6323
6517
 
6324
- if (!this.session.sampled) {
6325
- // If session was not sampled, then we do not initialize the integration at all.
6326
- return;
6327
- }
6518
+ const previousSessionId = this.session && this.session.id;
6328
6519
 
6329
- // If session is sampled for errors, then we need to set the recordingMode
6330
- // to 'error', which will configure recording with different options.
6331
- if (this.session.sampled === 'error') {
6332
- this.recordingMode = 'error';
6520
+ const { session } = getSession({
6521
+ timeouts: this.timeouts,
6522
+ stickySession: Boolean(this._options.stickySession),
6523
+ currentSession: this.session,
6524
+ // This is intentional: create a new session-based replay when calling `start()`
6525
+ sessionSampleRate: 1,
6526
+ allowBuffering: false,
6527
+ });
6528
+
6529
+ session.previousSessionId = previousSessionId;
6530
+ this.session = session;
6531
+
6532
+ this._initializeRecording();
6533
+ }
6534
+
6535
+ /**
6536
+ * Start replay buffering. Buffers until `flush()` is called or, if
6537
+ * `replaysOnErrorSampleRate` > 0, an error occurs.
6538
+ */
6539
+ startBuffering() {
6540
+ if (this._isEnabled) {
6541
+ throw new Error('Replay recording is already in progress');
6333
6542
  }
6334
6543
 
6335
- // setup() is generally called on page load or manually - in both cases we
6336
- // should treat it as an activity
6337
- this._updateSessionActivity();
6544
+ const previousSessionId = this.session && this.session.id;
6338
6545
 
6339
- this.eventBuffer = createEventBuffer({
6340
- useCompression: this._options.useCompression,
6546
+ const { session } = getSession({
6547
+ timeouts: this.timeouts,
6548
+ stickySession: Boolean(this._options.stickySession),
6549
+ currentSession: this.session,
6550
+ sessionSampleRate: 0,
6551
+ allowBuffering: true,
6341
6552
  });
6342
6553
 
6343
- this._addListeners();
6344
-
6345
- // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout
6346
- this._isEnabled = true;
6554
+ session.previousSessionId = previousSessionId;
6555
+ this.session = session;
6347
6556
 
6348
- this.startRecording();
6557
+ this.recordingMode = 'buffer';
6558
+ this._initializeRecording();
6349
6559
  }
6350
6560
 
6351
6561
  /**
@@ -6360,7 +6570,7 @@ class ReplayContainer {
6360
6570
  // When running in error sampling mode, we need to overwrite `checkoutEveryNms`
6361
6571
  // Without this, it would record forever, until an error happens, which we don't want
6362
6572
  // instead, we'll always keep the last 60 seconds of replay before an error happened
6363
- ...(this.recordingMode === 'error' && { checkoutEveryNms: ERROR_CHECKOUT_TIME }),
6573
+ ...(this.recordingMode === 'buffer' && { checkoutEveryNms: BUFFER_CHECKOUT_TIME }),
6364
6574
  emit: getHandleRecordingEmit(this),
6365
6575
  onMutation: this._onMutationHandler,
6366
6576
  });
@@ -6371,17 +6581,18 @@ class ReplayContainer {
6371
6581
 
6372
6582
  /**
6373
6583
  * Stops the recording, if it was running.
6374
- * Returns true if it was stopped, else false.
6584
+ *
6585
+ * Returns true if it was previously stopped, or is now stopped,
6586
+ * otherwise false.
6375
6587
  */
6376
6588
  stopRecording() {
6377
6589
  try {
6378
6590
  if (this._stopRecording) {
6379
6591
  this._stopRecording();
6380
6592
  this._stopRecording = undefined;
6381
- return true;
6382
6593
  }
6383
6594
 
6384
- return false;
6595
+ return true;
6385
6596
  } catch (err) {
6386
6597
  this._handleException(err);
6387
6598
  return false;
@@ -6392,7 +6603,7 @@ class ReplayContainer {
6392
6603
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK
6393
6604
  * does not support a teardown
6394
6605
  */
6395
- stop(reason) {
6606
+ async stop(reason) {
6396
6607
  if (!this._isEnabled) {
6397
6608
  return;
6398
6609
  }
@@ -6408,12 +6619,24 @@ class ReplayContainer {
6408
6619
  log(msg);
6409
6620
  }
6410
6621
 
6622
+ // We can't move `_isEnabled` after awaiting a flush, otherwise we can
6623
+ // enter into an infinite loop when `stop()` is called while flushing.
6411
6624
  this._isEnabled = false;
6412
6625
  this._removeListeners();
6413
6626
  this.stopRecording();
6627
+
6628
+ this._debouncedFlush.cancel();
6629
+ // See comment above re: `_isEnabled`, we "force" a flush, ignoring the
6630
+ // `_isEnabled` state of the plugin since it was disabled above.
6631
+ await this._flush({ force: true });
6632
+
6633
+ // After flush, destroy event buffer
6414
6634
  this.eventBuffer && this.eventBuffer.destroy();
6415
6635
  this.eventBuffer = null;
6416
- this._debouncedFlush.cancel();
6636
+
6637
+ // Clear session from session storage, note this means if a new session
6638
+ // is started after, it will not have `previousSessionId`
6639
+ clearSession(this);
6417
6640
  } catch (err) {
6418
6641
  this._handleException(err);
6419
6642
  }
@@ -6444,6 +6667,45 @@ class ReplayContainer {
6444
6667
  this.startRecording();
6445
6668
  }
6446
6669
 
6670
+ /**
6671
+ * If not in "session" recording mode, flush event buffer which will create a new replay.
6672
+ * Unless `continueRecording` is false, the replay will continue to record and
6673
+ * behave as a "session"-based replay.
6674
+ *
6675
+ * Otherwise, queue up a flush.
6676
+ */
6677
+ async sendBufferedReplayOrFlush({ continueRecording = true } = {}) {
6678
+ if (this.recordingMode === 'session') {
6679
+ return this.flushImmediate();
6680
+ }
6681
+
6682
+ // Allow flush to complete before resuming as a session recording, otherwise
6683
+ // the checkout from `startRecording` may be included in the payload.
6684
+ // Prefer to keep the error replay as a separate (and smaller) segment
6685
+ // than the session replay.
6686
+ await this.flushImmediate();
6687
+
6688
+ const hasStoppedRecording = this.stopRecording();
6689
+
6690
+ if (!continueRecording || !hasStoppedRecording) {
6691
+ return;
6692
+ }
6693
+
6694
+ // Re-start recording, but in "session" recording mode
6695
+
6696
+ // Reset all "capture on error" configuration before
6697
+ // starting a new recording
6698
+ this.recordingMode = 'session';
6699
+
6700
+ // Once this session ends, we do not want to refresh it
6701
+ if (this.session) {
6702
+ this.session.shouldRefresh = false;
6703
+ this._maybeSaveSession();
6704
+ }
6705
+
6706
+ this.startRecording();
6707
+ }
6708
+
6447
6709
  /**
6448
6710
  * We want to batch uploads of replay events. Save events only if
6449
6711
  * `<flushMinDelay>` milliseconds have elapsed since the last event
@@ -6453,12 +6715,12 @@ class ReplayContainer {
6453
6715
  * processing and hand back control to caller.
6454
6716
  */
6455
6717
  addUpdate(cb) {
6456
- // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'error'`)
6718
+ // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)
6457
6719
  const cbResult = cb();
6458
6720
 
6459
6721
  // If this option is turned on then we will only want to call `flush`
6460
6722
  // explicitly
6461
- if (this.recordingMode === 'error') {
6723
+ if (this.recordingMode === 'buffer') {
6462
6724
  return;
6463
6725
  }
6464
6726
 
@@ -6530,12 +6792,12 @@ class ReplayContainer {
6530
6792
  const oldSessionId = this.getSessionId();
6531
6793
 
6532
6794
  // Prevent starting a new session if the last user activity is older than
6533
- // SESSION_IDLE_DURATION. Otherwise non-user activity can trigger a new
6795
+ // SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new
6534
6796
  // session+recording. This creates noisy replays that do not have much
6535
6797
  // content in them.
6536
6798
  if (
6537
6799
  this._lastActivity &&
6538
- isExpired(this._lastActivity, this.timeouts.sessionIdle) &&
6800
+ isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&
6539
6801
  this.session &&
6540
6802
  this.session.sampled === 'session'
6541
6803
  ) {
@@ -6585,6 +6847,30 @@ class ReplayContainer {
6585
6847
  this._context.urls.push(url);
6586
6848
  }
6587
6849
 
6850
+ /**
6851
+ * Initialize and start all listeners to varying events (DOM,
6852
+ * Performance Observer, Recording, Sentry SDK, etc)
6853
+ */
6854
+ _initializeRecording() {
6855
+ this.setInitialState();
6856
+
6857
+ // this method is generally called on page load or manually - in both cases
6858
+ // we should treat it as an activity
6859
+ this._updateSessionActivity();
6860
+
6861
+ this.eventBuffer = createEventBuffer({
6862
+ useCompression: this._options.useCompression,
6863
+ });
6864
+
6865
+ this._removeListeners();
6866
+ this._addListeners();
6867
+
6868
+ // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout
6869
+ this._isEnabled = true;
6870
+
6871
+ this.startRecording();
6872
+ }
6873
+
6588
6874
  /** A wrapper to conditionally capture exceptions. */
6589
6875
  _handleException(error) {
6590
6876
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('[Replay]', error);
@@ -6604,7 +6890,7 @@ class ReplayContainer {
6604
6890
  stickySession: Boolean(this._options.stickySession),
6605
6891
  currentSession: this.session,
6606
6892
  sessionSampleRate: this._options.sessionSampleRate,
6607
- errorSampleRate: this._options.errorSampleRate,
6893
+ allowBuffering: this._options.errorSampleRate > 0,
6608
6894
  });
6609
6895
 
6610
6896
  // If session was newly created (i.e. was not loaded from storage), then
@@ -6621,7 +6907,7 @@ class ReplayContainer {
6621
6907
  this.session = session;
6622
6908
 
6623
6909
  if (!this.session.sampled) {
6624
- this.stop('session unsampled');
6910
+ void this.stop('session unsampled');
6625
6911
  return false;
6626
6912
  }
6627
6913
 
@@ -6745,7 +7031,7 @@ class ReplayContainer {
6745
7031
  const isSessionActive = this.checkAndHandleExpiredSession();
6746
7032
 
6747
7033
  if (!isSessionActive) {
6748
- // If the user has come back to the page within SESSION_IDLE_DURATION
7034
+ // If the user has come back to the page within SESSION_IDLE_PAUSE_DURATION
6749
7035
  // ms, we will re-use the existing session, otherwise create a new
6750
7036
  // session
6751
7037
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Replay] Document has become active, but session has expired');
@@ -6819,7 +7105,7 @@ class ReplayContainer {
6819
7105
  * Only flush if `this.recordingMode === 'session'`
6820
7106
  */
6821
7107
  _conditionalFlush() {
6822
- if (this.recordingMode === 'error') {
7108
+ if (this.recordingMode === 'buffer') {
6823
7109
  return;
6824
7110
  }
6825
7111
 
@@ -6834,22 +7120,35 @@ class ReplayContainer {
6834
7120
  this._context.errorIds.clear();
6835
7121
  this._context.traceIds.clear();
6836
7122
  this._context.urls = [];
6837
- this._context.earliestEvent = null;
7123
+ }
7124
+
7125
+ /** Update the initial timestamp based on the buffer content. */
7126
+ _updateInitialTimestampFromEventBuffer() {
7127
+ const { session, eventBuffer } = this;
7128
+ if (!session || !eventBuffer) {
7129
+ return;
7130
+ }
7131
+
7132
+ // we only ever update this on the initial segment
7133
+ if (session.segmentId) {
7134
+ return;
7135
+ }
7136
+
7137
+ const earliestEvent = eventBuffer.getEarliestTimestamp();
7138
+ if (earliestEvent && earliestEvent < this._context.initialTimestamp) {
7139
+ this._context.initialTimestamp = earliestEvent;
7140
+ }
6838
7141
  }
6839
7142
 
6840
7143
  /**
6841
7144
  * Return and clear _context
6842
7145
  */
6843
7146
  _popEventContext() {
6844
- if (this._context.earliestEvent && this._context.earliestEvent < this._context.initialTimestamp) {
6845
- this._context.initialTimestamp = this._context.earliestEvent;
6846
- }
6847
-
6848
7147
  const _context = {
6849
7148
  initialTimestamp: this._context.initialTimestamp,
6850
7149
  initialUrl: this._context.initialUrl,
6851
- errorIds: Array.from(this._context.errorIds).filter(Boolean),
6852
- traceIds: Array.from(this._context.traceIds).filter(Boolean),
7150
+ errorIds: Array.from(this._context.errorIds),
7151
+ traceIds: Array.from(this._context.traceIds),
6853
7152
  urls: this._context.urls,
6854
7153
  };
6855
7154
 
@@ -6888,6 +7187,9 @@ class ReplayContainer {
6888
7187
  }
6889
7188
 
6890
7189
  try {
7190
+ // This uses the data from the eventBuffer, so we need to call this before `finish()
7191
+ this._updateInitialTimestampFromEventBuffer();
7192
+
6891
7193
  // Note this empties the event buffer regardless of outcome of sending replay
6892
7194
  const recordingData = await this.eventBuffer.finish();
6893
7195
 
@@ -6914,7 +7216,7 @@ class ReplayContainer {
6914
7216
  // This means we retried 3 times and all of them failed,
6915
7217
  // or we ran into a problem we don't want to retry, like rate limiting.
6916
7218
  // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments
6917
- this.stop('sendReplay');
7219
+ void this.stop('sendReplay');
6918
7220
 
6919
7221
  const client = core.getCurrentHub().getClient();
6920
7222
 
@@ -6928,8 +7230,12 @@ class ReplayContainer {
6928
7230
  * Flush recording data to Sentry. Creates a lock so that only a single flush
6929
7231
  * can be active at a time. Do not call this directly.
6930
7232
  */
6931
- __init16() {this._flush = async () => {
6932
- if (!this._isEnabled) {
7233
+ __init16() {this._flush = async ({
7234
+ force = false,
7235
+ }
7236
+
7237
+ = {}) => {
7238
+ if (!this._isEnabled && !force) {
6933
7239
  // This can happen if e.g. the replay was stopped because of exceeding the retry limit
6934
7240
  return;
6935
7241
  }
@@ -7010,23 +7316,6 @@ class ReplayContainer {
7010
7316
  };}
7011
7317
  }
7012
7318
 
7013
- function _getExperimentalOptions(options) {
7014
- const requestHeaders = options._experiments.captureRequestHeaders || [];
7015
- const responseHeaders = options._experiments.captureResponseHeaders || [];
7016
- const captureBodies = options._experiments.captureNetworkBodies || false;
7017
-
7018
- // Add defaults
7019
- const defaultHeaders = ['content-length', 'content-type', 'accept'];
7020
-
7021
- return {
7022
- network: {
7023
- captureBodies,
7024
- requestHeaders: [...defaultHeaders, ...requestHeaders.map(header => header.toLowerCase())],
7025
- responseHeaders: [...defaultHeaders, ...responseHeaders.map(header => header.toLowerCase())],
7026
- },
7027
- };
7028
- }
7029
-
7030
7319
  function getOption(
7031
7320
  selectors,
7032
7321
  defaultSelectors,
@@ -7130,6 +7419,8 @@ function isElectronNodeRenderer() {
7130
7419
  const MEDIA_SELECTORS =
7131
7420
  'img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]';
7132
7421
 
7422
+ const DEFAULT_NETWORK_HEADERS = ['content-length', 'content-type', 'accept'];
7423
+
7133
7424
  let _initialized = false;
7134
7425
 
7135
7426
  /**
@@ -7170,6 +7461,11 @@ class Replay {
7170
7461
  maskAllInputs = true,
7171
7462
  blockAllMedia = true,
7172
7463
 
7464
+ networkDetailAllowUrls = [],
7465
+ networkCaptureBodies = true,
7466
+ networkRequestHeaders = [],
7467
+ networkResponseHeaders = [],
7468
+
7173
7469
  mask = [],
7174
7470
  unmask = [],
7175
7471
  block = [],
@@ -7228,6 +7524,11 @@ class Replay {
7228
7524
  errorSampleRate,
7229
7525
  useCompression,
7230
7526
  blockAllMedia,
7527
+ networkDetailAllowUrls,
7528
+ networkCaptureBodies,
7529
+ networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),
7530
+ networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),
7531
+
7231
7532
  _experiments,
7232
7533
  };
7233
7534
 
@@ -7281,14 +7582,7 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
7281
7582
  }
7282
7583
 
7283
7584
  /**
7284
- * We previously used to create a transaction in `setupOnce` and it would
7285
- * potentially create a transaction before some native SDK integrations have run
7286
- * and applied their own global event processor. An example is:
7287
- * https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
7288
- *
7289
- * So we call `replay.setup` in next event loop as a workaround to wait for other
7290
- * global event processors to finish. This is no longer needed, but keeping it
7291
- * here to avoid any future issues.
7585
+ * Setup and initialize replay container
7292
7586
  */
7293
7587
  setupOnce() {
7294
7588
  if (!isBrowser()) {
@@ -7297,12 +7591,20 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
7297
7591
 
7298
7592
  this._setup();
7299
7593
 
7300
- // XXX: See method comments above
7301
- setTimeout(() => this.start());
7594
+ // Once upon a time, we tried to create a transaction in `setupOnce` and it would
7595
+ // potentially create a transaction before some native SDK integrations have run
7596
+ // and applied their own global event processor. An example is:
7597
+ // https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
7598
+ //
7599
+ // So we call `this._initialize()` in next event loop as a workaround to wait for other
7600
+ // global event processors to finish. This is no longer needed, but keeping it
7601
+ // here to avoid any future issues.
7602
+ setTimeout(() => this._initialize());
7302
7603
  }
7303
7604
 
7304
7605
  /**
7305
- * Initializes the plugin.
7606
+ * Start a replay regardless of sampling rate. Calling this will always
7607
+ * create a new session. Will throw an error if replay is already in progress.
7306
7608
  *
7307
7609
  * Creates or loads a session, attaches listeners to varying events (DOM,
7308
7610
  * PerformanceObserver, Recording, Sentry SDK, etc)
@@ -7315,27 +7617,43 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
7315
7617
  this._replay.start();
7316
7618
  }
7317
7619
 
7620
+ /**
7621
+ * Start replay buffering. Buffers until `flush()` is called or, if
7622
+ * `replaysOnErrorSampleRate` > 0, until an error occurs.
7623
+ */
7624
+ startBuffering() {
7625
+ if (!this._replay) {
7626
+ return;
7627
+ }
7628
+
7629
+ this._replay.startBuffering();
7630
+ }
7631
+
7318
7632
  /**
7319
7633
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK
7320
7634
  * does not support a teardown
7321
7635
  */
7322
7636
  stop() {
7323
7637
  if (!this._replay) {
7324
- return;
7638
+ return Promise.resolve();
7325
7639
  }
7326
7640
 
7327
- this._replay.stop();
7641
+ return this._replay.stop();
7328
7642
  }
7329
7643
 
7330
7644
  /**
7331
- * Immediately send all pending events.
7645
+ * If not in "session" recording mode, flush event buffer which will create a new replay.
7646
+ * Unless `continueRecording` is false, the replay will continue to record and
7647
+ * behave as a "session"-based replay.
7648
+ *
7649
+ * Otherwise, queue up a flush.
7332
7650
  */
7333
- flush() {
7651
+ flush(options) {
7334
7652
  if (!this._replay || !this._replay.isEnabled()) {
7335
- return;
7653
+ return Promise.resolve();
7336
7654
  }
7337
7655
 
7338
- return this._replay.flushImmediate();
7656
+ return this._replay.sendBufferedReplayOrFlush(options);
7339
7657
  }
7340
7658
 
7341
7659
  /**
@@ -7348,6 +7666,16 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
7348
7666
 
7349
7667
  return this._replay.getSessionId();
7350
7668
  }
7669
+ /**
7670
+ * Initializes replay.
7671
+ */
7672
+ _initialize() {
7673
+ if (!this._replay) {
7674
+ return;
7675
+ }
7676
+
7677
+ this._replay.initializeSampling();
7678
+ }
7351
7679
 
7352
7680
  /** Setup the integration. */
7353
7681
  _setup() {
@@ -7397,5 +7725,9 @@ function loadReplayOptionsFromClient(initialOptions) {
7397
7725
  return finalOptions;
7398
7726
  }
7399
7727
 
7728
+ function _getMergedNetworkHeaders(headers) {
7729
+ return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];
7730
+ }
7731
+
7400
7732
  exports.Replay = Replay;
7401
7733
  //# sourceMappingURL=index.js.map