@sentry/replay 7.48.0 → 7.50.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 (39) hide show
  1. package/README.md +19 -6
  2. package/cjs/index.js +888 -200
  3. package/cjs/index.js.map +1 -1
  4. package/esm/index.js +889 -201
  5. package/esm/index.js.map +1 -1
  6. package/package.json +5 -5
  7. package/types/constants.d.ts +5 -3
  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/addBreadcrumbEvent.d.ts.map +1 -1
  14. package/types/coreHandlers/util/fetchUtils.d.ts.map +1 -1
  15. package/types/coreHandlers/util/networkUtils.d.ts +5 -1
  16. package/types/coreHandlers/util/networkUtils.d.ts.map +1 -1
  17. package/types/coreHandlers/util/xhrUtils.d.ts.map +1 -1
  18. package/types/integration.d.ts +21 -14
  19. package/types/integration.d.ts.map +1 -1
  20. package/types/replay.d.ts +33 -12
  21. package/types/replay.d.ts.map +1 -1
  22. package/types/session/Session.d.ts +0 -4
  23. package/types/session/Session.d.ts.map +1 -1
  24. package/types/session/clearSession.d.ts +6 -0
  25. package/types/session/clearSession.d.ts.map +1 -0
  26. package/types/session/createSession.d.ts +6 -2
  27. package/types/session/createSession.d.ts.map +1 -1
  28. package/types/session/getSession.d.ts +1 -1
  29. package/types/session/getSession.d.ts.map +1 -1
  30. package/types/types.d.ts +60 -38
  31. package/types/types.d.ts.map +1 -1
  32. package/types/util/truncateJson/completeJson.d.ts +9 -0
  33. package/types/util/truncateJson/completeJson.d.ts.map +1 -0
  34. package/types/util/truncateJson/constants.d.ts +12 -0
  35. package/types/util/truncateJson/constants.d.ts.map +1 -0
  36. package/types/util/truncateJson/evaluateJson.d.ts +6 -0
  37. package/types/util/truncateJson/evaluateJson.d.ts.map +1 -0
  38. package/types/util/truncateJson/fixJson.d.ts +6 -0
  39. package/types/util/truncateJson/fixJson.d.ts.map +1 -0
package/esm/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { getCurrentHub, addBreadcrumb, addGlobalEventProcessor, prepareEvent, setContext, captureException } from '@sentry/core';
2
- import { GLOBAL_OBJ, logger, uuid4, normalize, htmlTreeAsString, SENTRY_XHR_DATA_KEY, dropUndefinedKeys, addInstrumentationHandler, browserPerformanceTimeOrigin, createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader, isNodeEnv } from '@sentry/utils';
2
+ import { GLOBAL_OBJ, logger, uuid4, normalize, htmlTreeAsString, SENTRY_XHR_DATA_KEY, dropUndefinedKeys, stringMatchesSomePattern, addInstrumentationHandler, browserPerformanceTimeOrigin, createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader, isNodeEnv } from '@sentry/utils';
3
3
 
4
4
  // exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`
5
5
  // prevents the browser package from being bundled in the CDN bundle, and avoids a
@@ -11,11 +11,14 @@ const REPLAY_SESSION_KEY = 'sentryReplaySession';
11
11
  const REPLAY_EVENT_NAME = 'replay_event';
12
12
  const UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';
13
13
 
14
- // The idle limit for a session
15
- const SESSION_IDLE_DURATION = 300000; // 5 minutes in ms
14
+ // The idle limit for a session after which recording is paused.
15
+ const SESSION_IDLE_PAUSE_DURATION = 300000; // 5 minutes in ms
16
+
17
+ // The idle limit for a session after which the session expires.
18
+ const SESSION_IDLE_EXPIRE_DURATION = 900000; // 15 minutes in ms
16
19
 
17
20
  // The maximum length of a session
18
- const MAX_SESSION_LIFE = 3600000; // 60 minutes
21
+ const MAX_SESSION_LIFE = 3600000; // 60 minutes in ms
19
22
 
20
23
  /** Default flush delays */
21
24
  const DEFAULT_FLUSH_MIN_DELAY = 5000;
@@ -24,13 +27,16 @@ const DEFAULT_FLUSH_MIN_DELAY = 5000;
24
27
  const DEFAULT_FLUSH_MAX_DELAY = 5500;
25
28
 
26
29
  /* How long to wait for error checkouts */
27
- const ERROR_CHECKOUT_TIME = 60000;
30
+ const BUFFER_CHECKOUT_TIME = 60000;
28
31
 
29
32
  const RETRY_BASE_INTERVAL = 5000;
30
33
  const RETRY_MAX_COUNT = 3;
31
34
 
32
- /* The max (uncompressed) size in bytes of a network body. Any body larger than this will be dropped. */
33
- const NETWORK_BODY_MAX_SIZE = 300000;
35
+ /* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */
36
+ const NETWORK_BODY_MAX_SIZE = 150000;
37
+
38
+ /* The max size of a single console arg that is captured. Any arg larger than this will be truncated. */
39
+ const CONSOLE_ARG_MAX_SIZE = 5000;
34
40
 
35
41
  var NodeType$1;
36
42
  (function (NodeType) {
@@ -3696,6 +3702,31 @@ function createEventBuffer({ useCompression }) {
3696
3702
  return new EventBufferArray();
3697
3703
  }
3698
3704
 
3705
+ /**
3706
+ * Removes the session from Session Storage and unsets session in replay instance
3707
+ */
3708
+ function clearSession(replay) {
3709
+ deleteSession();
3710
+ replay.session = undefined;
3711
+ }
3712
+
3713
+ /**
3714
+ * Deletes a session from storage
3715
+ */
3716
+ function deleteSession() {
3717
+ const hasSessionStorage = 'sessionStorage' in WINDOW;
3718
+
3719
+ if (!hasSessionStorage) {
3720
+ return;
3721
+ }
3722
+
3723
+ try {
3724
+ WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY);
3725
+ } catch (e) {
3726
+ // Ignore potential SecurityError exceptions
3727
+ }
3728
+ }
3729
+
3699
3730
  /**
3700
3731
  * Given an initial timestamp and an expiry duration, checks to see if current
3701
3732
  * time should be considered as expired.
@@ -3726,11 +3757,26 @@ function isSessionExpired(session, timeouts, targetTime = +new Date()) {
3726
3757
  // First, check that maximum session length has not been exceeded
3727
3758
  isExpired(session.started, timeouts.maxSessionLife, targetTime) ||
3728
3759
  // check that the idle timeout has not been exceeded (i.e. user has
3729
- // performed an action within the last `idleTimeout` ms)
3730
- isExpired(session.lastActivity, timeouts.sessionIdle, targetTime)
3760
+ // performed an action within the last `sessionIdleExpire` ms)
3761
+ isExpired(session.lastActivity, timeouts.sessionIdleExpire, targetTime)
3731
3762
  );
3732
3763
  }
3733
3764
 
3765
+ /**
3766
+ * Given a sample rate, returns true if replay should be sampled.
3767
+ *
3768
+ * 1.0 = 100% sampling
3769
+ * 0.0 = 0% sampling
3770
+ */
3771
+ function isSampled(sampleRate) {
3772
+ if (sampleRate === undefined) {
3773
+ return false;
3774
+ }
3775
+
3776
+ // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)
3777
+ return Math.random() < sampleRate;
3778
+ }
3779
+
3734
3780
  /**
3735
3781
  * Save a session to session storage.
3736
3782
  */
@@ -3747,21 +3793,6 @@ function saveSession(session) {
3747
3793
  }
3748
3794
  }
3749
3795
 
3750
- /**
3751
- * Given a sample rate, returns true if replay should be sampled.
3752
- *
3753
- * 1.0 = 100% sampling
3754
- * 0.0 = 0% sampling
3755
- */
3756
- function isSampled(sampleRate) {
3757
- if (sampleRate === undefined) {
3758
- return false;
3759
- }
3760
-
3761
- // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)
3762
- return Math.random() < sampleRate;
3763
- }
3764
-
3765
3796
  /**
3766
3797
  * Get a session with defaults & applied sampling.
3767
3798
  */
@@ -3780,14 +3811,15 @@ function makeSession(session) {
3780
3811
  lastActivity,
3781
3812
  segmentId,
3782
3813
  sampled,
3814
+ shouldRefresh: true,
3783
3815
  };
3784
3816
  }
3785
3817
 
3786
3818
  /**
3787
3819
  * Get the sampled status for a session based on sample rates & current sampled status.
3788
3820
  */
3789
- function getSessionSampleType(sessionSampleRate, errorSampleRate) {
3790
- return isSampled(sessionSampleRate) ? 'session' : isSampled(errorSampleRate) ? 'error' : false;
3821
+ function getSessionSampleType(sessionSampleRate, allowBuffering) {
3822
+ return isSampled(sessionSampleRate) ? 'session' : allowBuffering ? 'buffer' : false;
3791
3823
  }
3792
3824
 
3793
3825
  /**
@@ -3795,8 +3827,8 @@ function getSessionSampleType(sessionSampleRate, errorSampleRate) {
3795
3827
  * that all replays will be saved to as attachments. Currently, we only expect
3796
3828
  * one of these Sentry events per "replay session".
3797
3829
  */
3798
- function createSession({ sessionSampleRate, errorSampleRate, stickySession = false }) {
3799
- const sampled = getSessionSampleType(sessionSampleRate, errorSampleRate);
3830
+ function createSession({ sessionSampleRate, allowBuffering, stickySession = false }) {
3831
+ const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);
3800
3832
  const session = makeSession({
3801
3833
  sampled,
3802
3834
  });
@@ -3844,7 +3876,7 @@ function getSession({
3844
3876
  currentSession,
3845
3877
  stickySession,
3846
3878
  sessionSampleRate,
3847
- errorSampleRate,
3879
+ allowBuffering,
3848
3880
  }) {
3849
3881
  // If session exists and is passed, use it instead of always hitting session storage
3850
3882
  const session = currentSession || (stickySession && fetchSession());
@@ -3857,8 +3889,9 @@ function getSession({
3857
3889
 
3858
3890
  if (!isExpired) {
3859
3891
  return { type: 'saved', session };
3860
- } else if (session.sampled === 'error') {
3861
- // Error samples should not be re-created when expired, but instead we stop when the replay is done
3892
+ } else if (!session.shouldRefresh) {
3893
+ // In this case, stop
3894
+ // This is the case if we have an error session that is completed (=triggered an error)
3862
3895
  const discardedSession = makeSession({ sampled: false });
3863
3896
  return { type: 'new', session: discardedSession };
3864
3897
  } else {
@@ -3870,7 +3903,7 @@ function getSession({
3870
3903
  const newSession = createSession({
3871
3904
  stickySession,
3872
3905
  sessionSampleRate,
3873
- errorSampleRate,
3906
+ allowBuffering,
3874
3907
  });
3875
3908
 
3876
3909
  return { type: 'new', session: newSession };
@@ -3904,7 +3937,7 @@ async function addEvent(
3904
3937
  // page has been left open and idle for a long period of time and user
3905
3938
  // comes back to trigger a new session. The performance entries rely on
3906
3939
  // `performance.timeOrigin`, which is when the page first opened.
3907
- if (timestampInMs + replay.timeouts.sessionIdle < Date.now()) {
3940
+ if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) {
3908
3941
  return null;
3909
3942
  }
3910
3943
 
@@ -3919,7 +3952,7 @@ async function addEvent(
3919
3952
  return await replay.eventBuffer.addEvent(event, isCheckout);
3920
3953
  } catch (error) {
3921
3954
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error(error);
3922
- replay.stop('addEvent');
3955
+ await replay.stop('addEvent');
3923
3956
 
3924
3957
  const client = getCurrentHub().getClient();
3925
3958
 
@@ -3986,23 +4019,17 @@ function handleAfterSendEvent(replay) {
3986
4019
  // Trigger error recording
3987
4020
  // Need to be very careful that this does not cause an infinite loop
3988
4021
  if (
3989
- replay.recordingMode === 'error' &&
4022
+ replay.recordingMode === 'buffer' &&
3990
4023
  event.exception &&
3991
4024
  event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because otherwise we could loop indefinitely with trying to capture replay and failing
3992
4025
  ) {
3993
- setTimeout(async () => {
3994
- // Allow flush to complete before resuming as a session recording, otherwise
3995
- // the checkout from `startRecording` may be included in the payload.
3996
- // Prefer to keep the error replay as a separate (and smaller) segment
3997
- // than the session replay.
3998
- await replay.flushImmediate();
3999
-
4000
- if (replay.stopRecording()) {
4001
- // Reset all "capture on error" configuration before
4002
- // starting a new recording
4003
- replay.recordingMode = 'session';
4004
- replay.startRecording();
4005
- }
4026
+ if (!isSampled(replay.getOptions().errorSampleRate)) {
4027
+ return;
4028
+ }
4029
+
4030
+ setTimeout(() => {
4031
+ // Capture current event buffer as new replay
4032
+ void replay.sendBufferedReplayOrFlush();
4006
4033
  });
4007
4034
  }
4008
4035
  };
@@ -4069,7 +4096,8 @@ function addBreadcrumbEvent(replay, breadcrumb) {
4069
4096
  timestamp: (breadcrumb.timestamp || 0) * 1000,
4070
4097
  data: {
4071
4098
  tag: 'breadcrumb',
4072
- payload: normalize(breadcrumb),
4099
+ // normalize to max. 10 depth and 1_000 properties per object
4100
+ payload: normalize(breadcrumb, 10, 1000),
4073
4101
  },
4074
4102
  });
4075
4103
 
@@ -4476,6 +4504,393 @@ function handleXhrSpanListener(replay) {
4476
4504
  };
4477
4505
  }
4478
4506
 
4507
+ const OBJ = 10;
4508
+ const OBJ_KEY = 11;
4509
+ const OBJ_KEY_STR = 12;
4510
+ const OBJ_VAL = 13;
4511
+ const OBJ_VAL_STR = 14;
4512
+ const OBJ_VAL_COMPLETED = 15;
4513
+
4514
+ const ARR = 20;
4515
+ const ARR_VAL = 21;
4516
+ const ARR_VAL_STR = 22;
4517
+ const ARR_VAL_COMPLETED = 23;
4518
+
4519
+ const ALLOWED_PRIMITIVES = ['true', 'false', 'null'];
4520
+
4521
+ /**
4522
+ * Complete an incomplete JSON string.
4523
+ * This will ensure that the last element always has a `"~~"` to indicate it was truncated.
4524
+ * For example, `[1,2,` will be completed to `[1,2,"~~"]`
4525
+ * and `{"aa":"b` will be completed to `{"aa":"b~~"}`
4526
+ */
4527
+ function completeJson(incompleteJson, stack) {
4528
+ if (!stack.length) {
4529
+ return incompleteJson;
4530
+ }
4531
+
4532
+ let json = incompleteJson;
4533
+
4534
+ // Most checks are only needed for the last step in the stack
4535
+ const lastPos = stack.length - 1;
4536
+ const lastStep = stack[lastPos];
4537
+
4538
+ json = _fixLastStep(json, lastStep);
4539
+
4540
+ // Complete remaining steps - just add closing brackets
4541
+ for (let i = lastPos; i >= 0; i--) {
4542
+ const step = stack[i];
4543
+
4544
+ switch (step) {
4545
+ case OBJ:
4546
+ json = `${json}}`;
4547
+ break;
4548
+ case ARR:
4549
+ json = `${json}]`;
4550
+ break;
4551
+ }
4552
+ }
4553
+
4554
+ return json;
4555
+ }
4556
+
4557
+ function _fixLastStep(json, lastStep) {
4558
+ switch (lastStep) {
4559
+ // Object cases
4560
+ case OBJ:
4561
+ return `${json}"~~":"~~"`;
4562
+ case OBJ_KEY:
4563
+ return `${json}:"~~"`;
4564
+ case OBJ_KEY_STR:
4565
+ return `${json}~~":"~~"`;
4566
+ case OBJ_VAL:
4567
+ return _maybeFixIncompleteObjValue(json);
4568
+ case OBJ_VAL_STR:
4569
+ return `${json}~~"`;
4570
+ case OBJ_VAL_COMPLETED:
4571
+ return `${json},"~~":"~~"`;
4572
+
4573
+ // Array cases
4574
+ case ARR:
4575
+ return `${json}"~~"`;
4576
+ case ARR_VAL:
4577
+ return _maybeFixIncompleteArrValue(json);
4578
+ case ARR_VAL_STR:
4579
+ return `${json}~~"`;
4580
+ case ARR_VAL_COMPLETED:
4581
+ return `${json},"~~"`;
4582
+ }
4583
+
4584
+ return json;
4585
+ }
4586
+
4587
+ function _maybeFixIncompleteArrValue(json) {
4588
+ const pos = _findLastArrayDelimiter(json);
4589
+
4590
+ if (pos > -1) {
4591
+ const part = json.slice(pos + 1);
4592
+
4593
+ if (ALLOWED_PRIMITIVES.includes(part.trim())) {
4594
+ return `${json},"~~"`;
4595
+ }
4596
+
4597
+ // Everything else is replaced with `"~~"`
4598
+ return `${json.slice(0, pos + 1)}"~~"`;
4599
+ }
4600
+
4601
+ // fallback, this shouldn't happen, to be save
4602
+ return json;
4603
+ }
4604
+
4605
+ function _findLastArrayDelimiter(json) {
4606
+ for (let i = json.length - 1; i >= 0; i--) {
4607
+ const char = json[i];
4608
+
4609
+ if (char === ',' || char === '[') {
4610
+ return i;
4611
+ }
4612
+ }
4613
+
4614
+ return -1;
4615
+ }
4616
+
4617
+ function _maybeFixIncompleteObjValue(json) {
4618
+ const startPos = json.lastIndexOf(':');
4619
+
4620
+ const part = json.slice(startPos + 1);
4621
+
4622
+ if (ALLOWED_PRIMITIVES.includes(part.trim())) {
4623
+ return `${json},"~~":"~~"`;
4624
+ }
4625
+
4626
+ // Everything else is replaced with `"~~"`
4627
+ // This also means we do not have incomplete numbers, e.g `[1` is replaced with `["~~"]`
4628
+ return `${json.slice(0, startPos + 1)}"~~"`;
4629
+ }
4630
+
4631
+ /**
4632
+ * Evaluate an (incomplete) JSON string.
4633
+ */
4634
+ function evaluateJson(json) {
4635
+ const stack = [];
4636
+
4637
+ for (let pos = 0; pos < json.length; pos++) {
4638
+ _evaluateJsonPos(stack, json, pos);
4639
+ }
4640
+
4641
+ return stack;
4642
+ }
4643
+
4644
+ function _evaluateJsonPos(stack, json, pos) {
4645
+ const curStep = stack[stack.length - 1];
4646
+
4647
+ const char = json[pos];
4648
+
4649
+ const whitespaceRegex = /\s/;
4650
+
4651
+ if (whitespaceRegex.test(char)) {
4652
+ return;
4653
+ }
4654
+
4655
+ if (char === '"' && !_isEscaped(json, pos)) {
4656
+ _handleQuote(stack, curStep);
4657
+ return;
4658
+ }
4659
+
4660
+ switch (char) {
4661
+ case '{':
4662
+ _handleObj(stack, curStep);
4663
+ break;
4664
+ case '[':
4665
+ _handleArr(stack, curStep);
4666
+ break;
4667
+ case ':':
4668
+ _handleColon(stack, curStep);
4669
+ break;
4670
+ case ',':
4671
+ _handleComma(stack, curStep);
4672
+ break;
4673
+ case '}':
4674
+ _handleObjClose(stack, curStep);
4675
+ break;
4676
+ case ']':
4677
+ _handleArrClose(stack, curStep);
4678
+ break;
4679
+ }
4680
+ }
4681
+
4682
+ function _handleQuote(stack, curStep) {
4683
+ // End of obj value
4684
+ if (curStep === OBJ_VAL_STR) {
4685
+ stack.pop();
4686
+ stack.push(OBJ_VAL_COMPLETED);
4687
+ return;
4688
+ }
4689
+
4690
+ // End of arr value
4691
+ if (curStep === ARR_VAL_STR) {
4692
+ stack.pop();
4693
+ stack.push(ARR_VAL_COMPLETED);
4694
+ return;
4695
+ }
4696
+
4697
+ // Start of obj value
4698
+ if (curStep === OBJ_VAL) {
4699
+ stack.push(OBJ_VAL_STR);
4700
+ return;
4701
+ }
4702
+
4703
+ // Start of arr value
4704
+ if (curStep === ARR_VAL) {
4705
+ stack.push(ARR_VAL_STR);
4706
+ return;
4707
+ }
4708
+
4709
+ // Start of obj key
4710
+ if (curStep === OBJ) {
4711
+ stack.push(OBJ_KEY_STR);
4712
+ return;
4713
+ }
4714
+
4715
+ // End of obj key
4716
+ if (curStep === OBJ_KEY_STR) {
4717
+ stack.pop();
4718
+ stack.push(OBJ_KEY);
4719
+ return;
4720
+ }
4721
+ }
4722
+
4723
+ function _handleObj(stack, curStep) {
4724
+ // Initial object
4725
+ if (!curStep) {
4726
+ stack.push(OBJ);
4727
+ return;
4728
+ }
4729
+
4730
+ // New object as obj value
4731
+ if (curStep === OBJ_VAL) {
4732
+ stack.push(OBJ);
4733
+ return;
4734
+ }
4735
+
4736
+ // New object as array element
4737
+ if (curStep === ARR_VAL) {
4738
+ stack.push(OBJ);
4739
+ }
4740
+
4741
+ // New object as first array element
4742
+ if (curStep === ARR) {
4743
+ stack.push(OBJ);
4744
+ return;
4745
+ }
4746
+ }
4747
+
4748
+ function _handleArr(stack, curStep) {
4749
+ // Initial array
4750
+ if (!curStep) {
4751
+ stack.push(ARR);
4752
+ stack.push(ARR_VAL);
4753
+ return;
4754
+ }
4755
+
4756
+ // New array as obj value
4757
+ if (curStep === OBJ_VAL) {
4758
+ stack.push(ARR);
4759
+ stack.push(ARR_VAL);
4760
+ return;
4761
+ }
4762
+
4763
+ // New array as array element
4764
+ if (curStep === ARR_VAL) {
4765
+ stack.push(ARR);
4766
+ stack.push(ARR_VAL);
4767
+ }
4768
+
4769
+ // New array as first array element
4770
+ if (curStep === ARR) {
4771
+ stack.push(ARR);
4772
+ stack.push(ARR_VAL);
4773
+ return;
4774
+ }
4775
+ }
4776
+
4777
+ function _handleColon(stack, curStep) {
4778
+ if (curStep === OBJ_KEY) {
4779
+ stack.pop();
4780
+ stack.push(OBJ_VAL);
4781
+ }
4782
+ }
4783
+
4784
+ function _handleComma(stack, curStep) {
4785
+ // Comma after obj value
4786
+ if (curStep === OBJ_VAL) {
4787
+ stack.pop();
4788
+ return;
4789
+ }
4790
+ if (curStep === OBJ_VAL_COMPLETED) {
4791
+ // Pop OBJ_VAL_COMPLETED & OBJ_VAL
4792
+ stack.pop();
4793
+ stack.pop();
4794
+ return;
4795
+ }
4796
+
4797
+ // Comma after arr value
4798
+ if (curStep === ARR_VAL) {
4799
+ // do nothing - basically we'd pop ARR_VAL but add it right back
4800
+ return;
4801
+ }
4802
+
4803
+ if (curStep === ARR_VAL_COMPLETED) {
4804
+ // Pop ARR_VAL_COMPLETED
4805
+ stack.pop();
4806
+
4807
+ // basically we'd pop ARR_VAL but add it right back
4808
+ return;
4809
+ }
4810
+ }
4811
+
4812
+ function _handleObjClose(stack, curStep) {
4813
+ // Empty object {}
4814
+ if (curStep === OBJ) {
4815
+ stack.pop();
4816
+ }
4817
+
4818
+ // Object with element
4819
+ if (curStep === OBJ_VAL) {
4820
+ // Pop OBJ_VAL, OBJ
4821
+ stack.pop();
4822
+ stack.pop();
4823
+ }
4824
+
4825
+ // Obj with element
4826
+ if (curStep === OBJ_VAL_COMPLETED) {
4827
+ // Pop OBJ_VAL_COMPLETED, OBJ_VAL, OBJ
4828
+ stack.pop();
4829
+ stack.pop();
4830
+ stack.pop();
4831
+ }
4832
+
4833
+ // if was obj value, complete it
4834
+ if (stack[stack.length - 1] === OBJ_VAL) {
4835
+ stack.push(OBJ_VAL_COMPLETED);
4836
+ }
4837
+
4838
+ // if was arr value, complete it
4839
+ if (stack[stack.length - 1] === ARR_VAL) {
4840
+ stack.push(ARR_VAL_COMPLETED);
4841
+ }
4842
+ }
4843
+
4844
+ function _handleArrClose(stack, curStep) {
4845
+ // Empty array []
4846
+ if (curStep === ARR) {
4847
+ stack.pop();
4848
+ }
4849
+
4850
+ // Array with element
4851
+ if (curStep === ARR_VAL) {
4852
+ // Pop ARR_VAL, ARR
4853
+ stack.pop();
4854
+ stack.pop();
4855
+ }
4856
+
4857
+ // Array with element
4858
+ if (curStep === ARR_VAL_COMPLETED) {
4859
+ // Pop ARR_VAL_COMPLETED, ARR_VAL, ARR
4860
+ stack.pop();
4861
+ stack.pop();
4862
+ stack.pop();
4863
+ }
4864
+
4865
+ // if was obj value, complete it
4866
+ if (stack[stack.length - 1] === OBJ_VAL) {
4867
+ stack.push(OBJ_VAL_COMPLETED);
4868
+ }
4869
+
4870
+ // if was arr value, complete it
4871
+ if (stack[stack.length - 1] === ARR_VAL) {
4872
+ stack.push(ARR_VAL_COMPLETED);
4873
+ }
4874
+ }
4875
+
4876
+ function _isEscaped(str, pos) {
4877
+ const previousChar = str[pos - 1];
4878
+
4879
+ return previousChar === '\\' && !_isEscaped(str, pos - 1);
4880
+ }
4881
+
4882
+ /* eslint-disable max-lines */
4883
+
4884
+ /**
4885
+ * Takes an incomplete JSON string, and returns a hopefully valid JSON string.
4886
+ * Note that this _can_ fail, so you should check the return value is valid JSON.
4887
+ */
4888
+ function fixJson(incompleteJson) {
4889
+ const stack = evaluateJson(incompleteJson);
4890
+
4891
+ return completeJson(incompleteJson, stack);
4892
+ }
4893
+
4479
4894
  /** Get the size of a body. */
4480
4895
  function getBodySize(
4481
4896
  body,
@@ -4569,19 +4984,15 @@ function makeNetworkReplayBreadcrumb(
4569
4984
  return result;
4570
4985
  }
4571
4986
 
4572
- /** Get either a JSON network body, or a text representation. */
4573
- function getNetworkBody(bodyText) {
4574
- if (!bodyText) {
4575
- return;
4576
- }
4577
-
4578
- try {
4579
- return JSON.parse(bodyText);
4580
- } catch (e2) {
4581
- // return text
4582
- }
4583
-
4584
- return bodyText;
4987
+ /** Build the request or response part of a replay network breadcrumb that was skipped. */
4988
+ function buildSkippedNetworkRequestOrResponse(bodySize) {
4989
+ return {
4990
+ headers: {},
4991
+ size: bodySize,
4992
+ _meta: {
4993
+ warnings: ['URL_SKIPPED'],
4994
+ },
4995
+ };
4585
4996
  }
4586
4997
 
4587
4998
  /** Build the request or response part of a replay network breadcrumb. */
@@ -4612,11 +5023,11 @@ function buildNetworkRequestOrResponse(
4612
5023
  size: bodySize,
4613
5024
  };
4614
5025
 
4615
- if (bodySize < NETWORK_BODY_MAX_SIZE) {
4616
- info.body = body;
4617
- } else {
5026
+ const { body: normalizedBody, warnings } = normalizeNetworkBody(body);
5027
+ info.body = normalizedBody;
5028
+ if (warnings.length > 0) {
4618
5029
  info._meta = {
4619
- errors: ['MAX_BODY_SIZE_EXCEEDED'],
5030
+ warnings,
4620
5031
  };
4621
5032
  }
4622
5033
 
@@ -4642,6 +5053,53 @@ function _serializeFormData(formData) {
4642
5053
  return new URLSearchParams(formData).toString();
4643
5054
  }
4644
5055
 
5056
+ function normalizeNetworkBody(body)
5057
+
5058
+ {
5059
+ if (!body || typeof body !== 'string') {
5060
+ return {
5061
+ body,
5062
+ warnings: [],
5063
+ };
5064
+ }
5065
+
5066
+ const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE;
5067
+
5068
+ if (_strIsProbablyJson(body)) {
5069
+ try {
5070
+ const json = exceedsSizeLimit ? fixJson(body.slice(0, NETWORK_BODY_MAX_SIZE)) : body;
5071
+ const normalizedBody = JSON.parse(json);
5072
+ return {
5073
+ body: normalizedBody,
5074
+ warnings: exceedsSizeLimit ? ['JSON_TRUNCATED'] : [],
5075
+ };
5076
+ } catch (e3) {
5077
+ return {
5078
+ body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,
5079
+ warnings: exceedsSizeLimit ? ['INVALID_JSON', 'TEXT_TRUNCATED'] : ['INVALID_JSON'],
5080
+ };
5081
+ }
5082
+ }
5083
+
5084
+ return {
5085
+ body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,
5086
+ warnings: exceedsSizeLimit ? ['TEXT_TRUNCATED'] : [],
5087
+ };
5088
+ }
5089
+
5090
+ function _strIsProbablyJson(str) {
5091
+ const first = str[0];
5092
+ const last = str[str.length - 1];
5093
+
5094
+ // Simple check: If this does not start & end with {} or [], it's not JSON
5095
+ return (first === '[' && last === ']') || (first === '{' && last === '}');
5096
+ }
5097
+
5098
+ /** Match an URL against a list of strings/Regex. */
5099
+ function urlMatches(url, urls) {
5100
+ return stringMatchesSomePattern(url, urls);
5101
+ }
5102
+
4645
5103
  /**
4646
5104
  * Capture a fetch breadcrumb to a replay.
4647
5105
  * This adds additional data (where approriate).
@@ -4701,56 +5159,65 @@ async function _prepareFetchData(
4701
5159
  const {
4702
5160
  url,
4703
5161
  method,
4704
- status_code: statusCode,
5162
+ status_code: statusCode = 0,
4705
5163
  request_body_size: requestBodySize,
4706
5164
  response_body_size: responseBodySize,
4707
5165
  } = breadcrumb.data;
4708
5166
 
4709
- const request = _getRequestInfo(options, hint.input, requestBodySize);
4710
- const response = await _getResponseInfo(options, hint.response, responseBodySize);
5167
+ const captureDetails = urlMatches(url, options.networkDetailAllowUrls);
5168
+
5169
+ const request = captureDetails
5170
+ ? _getRequestInfo(options, hint.input, requestBodySize)
5171
+ : buildSkippedNetworkRequestOrResponse(requestBodySize);
5172
+ const response = await _getResponseInfo(captureDetails, options, hint.response, responseBodySize);
4711
5173
 
4712
5174
  return {
4713
5175
  startTimestamp,
4714
5176
  endTimestamp,
4715
5177
  url,
4716
5178
  method,
4717
- statusCode: statusCode || 0,
5179
+ statusCode,
4718
5180
  request,
4719
5181
  response,
4720
5182
  };
4721
5183
  }
4722
5184
 
4723
5185
  function _getRequestInfo(
4724
- { captureBodies, requestHeaders },
5186
+ { networkCaptureBodies, networkRequestHeaders },
4725
5187
  input,
4726
5188
  requestBodySize,
4727
5189
  ) {
4728
- const headers = getRequestHeaders(input, requestHeaders);
5190
+ const headers = getRequestHeaders(input, networkRequestHeaders);
4729
5191
 
4730
- if (!captureBodies) {
5192
+ if (!networkCaptureBodies) {
4731
5193
  return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);
4732
5194
  }
4733
5195
 
4734
5196
  // We only want to transmit string or string-like bodies
4735
5197
  const requestBody = _getFetchRequestArgBody(input);
4736
- const body = getNetworkBody(getBodyString(requestBody));
4737
- return buildNetworkRequestOrResponse(headers, requestBodySize, body);
5198
+ const bodyStr = getBodyString(requestBody);
5199
+ return buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);
4738
5200
  }
4739
5201
 
4740
5202
  async function _getResponseInfo(
5203
+ captureDetails,
4741
5204
  {
4742
- captureBodies,
5205
+ networkCaptureBodies,
4743
5206
  textEncoder,
4744
- responseHeaders,
5207
+ networkResponseHeaders,
4745
5208
  }
4746
5209
 
4747
5210
  ,
4748
5211
  response,
4749
5212
  responseBodySize,
4750
5213
  ) {
4751
- const headers = getAllHeaders(response.headers, responseHeaders);
5214
+ if (!captureDetails && responseBodySize !== undefined) {
5215
+ return buildSkippedNetworkRequestOrResponse(responseBodySize);
5216
+ }
4752
5217
 
4753
- if (!captureBodies && responseBodySize !== undefined) {
5218
+ const headers = getAllHeaders(response.headers, networkResponseHeaders);
5219
+
5220
+ if (!networkCaptureBodies && responseBodySize !== undefined) {
4754
5221
  return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);
4755
5222
  }
4756
5223
 
@@ -4758,15 +5225,19 @@ async function _getResponseInfo(
4758
5225
  try {
4759
5226
  // We have to clone this, as the body can only be read once
4760
5227
  const res = response.clone();
4761
- const { body, bodyText } = await _parseFetchBody(res);
5228
+ const bodyText = await _parseFetchBody(res);
4762
5229
 
4763
5230
  const size =
4764
5231
  bodyText && bodyText.length && responseBodySize === undefined
4765
5232
  ? getBodySize(bodyText, textEncoder)
4766
5233
  : responseBodySize;
4767
5234
 
4768
- if (captureBodies) {
4769
- return buildNetworkRequestOrResponse(headers, size, body);
5235
+ if (!captureDetails) {
5236
+ return buildSkippedNetworkRequestOrResponse(size);
5237
+ }
5238
+
5239
+ if (networkCaptureBodies) {
5240
+ return buildNetworkRequestOrResponse(headers, size, bodyText);
4770
5241
  }
4771
5242
 
4772
5243
  return buildNetworkRequestOrResponse(headers, size, undefined);
@@ -4776,25 +5247,12 @@ async function _getResponseInfo(
4776
5247
  }
4777
5248
  }
4778
5249
 
4779
- async function _parseFetchBody(
4780
- response,
4781
- ) {
4782
- let bodyText;
4783
-
5250
+ async function _parseFetchBody(response) {
4784
5251
  try {
4785
- bodyText = await response.text();
5252
+ return await response.text();
4786
5253
  } catch (e2) {
4787
- return {};
4788
- }
4789
-
4790
- try {
4791
- const body = JSON.parse(bodyText);
4792
- return { body, bodyText };
4793
- } catch (e3) {
4794
- // just send bodyText
5254
+ return undefined;
4795
5255
  }
4796
-
4797
- return { bodyText, body: bodyText };
4798
5256
  }
4799
5257
 
4800
5258
  function _getFetchRequestArgBody(fetchArgs = []) {
@@ -4911,28 +5369,44 @@ function _prepareXhrData(
4911
5369
  const {
4912
5370
  url,
4913
5371
  method,
4914
- status_code: statusCode,
5372
+ status_code: statusCode = 0,
4915
5373
  request_body_size: requestBodySize,
4916
5374
  response_body_size: responseBodySize,
4917
5375
  } = breadcrumb.data;
4918
5376
 
4919
- const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];
4920
- const requestHeaders = xhrInfo ? getAllowedHeaders(xhrInfo.request_headers, options.requestHeaders) : {};
4921
- const responseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.responseHeaders);
4922
-
4923
5377
  if (!url) {
4924
5378
  return null;
4925
5379
  }
4926
5380
 
5381
+ if (!urlMatches(url, options.networkDetailAllowUrls)) {
5382
+ const request = buildSkippedNetworkRequestOrResponse(requestBodySize);
5383
+ const response = buildSkippedNetworkRequestOrResponse(responseBodySize);
5384
+ return {
5385
+ startTimestamp,
5386
+ endTimestamp,
5387
+ url,
5388
+ method,
5389
+ statusCode,
5390
+ request,
5391
+ response,
5392
+ };
5393
+ }
5394
+
5395
+ const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];
5396
+ const networkRequestHeaders = xhrInfo
5397
+ ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders)
5398
+ : {};
5399
+ const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.networkResponseHeaders);
5400
+
4927
5401
  const request = buildNetworkRequestOrResponse(
4928
- requestHeaders,
5402
+ networkRequestHeaders,
4929
5403
  requestBodySize,
4930
- options.captureBodies ? getNetworkBody(getBodyString(input)) : undefined,
5404
+ options.networkCaptureBodies ? getBodyString(input) : undefined,
4931
5405
  );
4932
5406
  const response = buildNetworkRequestOrResponse(
4933
- responseHeaders,
5407
+ networkResponseHeaders,
4934
5408
  responseBodySize,
4935
- options.captureBodies ? getNetworkBody(hint.xhr.responseText) : undefined,
5409
+ options.networkCaptureBodies ? hint.xhr.responseText : undefined,
4936
5410
  );
4937
5411
 
4938
5412
  return {
@@ -4940,7 +5414,7 @@ function _prepareXhrData(
4940
5414
  endTimestamp,
4941
5415
  url,
4942
5416
  method,
4943
- statusCode: statusCode || 0,
5417
+ statusCode,
4944
5418
  request,
4945
5419
  response,
4946
5420
  };
@@ -4972,10 +5446,16 @@ function handleNetworkBreadcrumbs(replay) {
4972
5446
  try {
4973
5447
  const textEncoder = new TextEncoder();
4974
5448
 
5449
+ const { networkDetailAllowUrls, networkCaptureBodies, networkRequestHeaders, networkResponseHeaders } =
5450
+ replay.getOptions();
5451
+
4975
5452
  const options = {
4976
5453
  replay,
4977
5454
  textEncoder,
4978
- ...replay.getExperimentalOptions().network,
5455
+ networkDetailAllowUrls,
5456
+ networkCaptureBodies,
5457
+ networkRequestHeaders,
5458
+ networkResponseHeaders,
4979
5459
  };
4980
5460
 
4981
5461
  if (client && client.on) {
@@ -5083,9 +5563,66 @@ function handleScope(scope) {
5083
5563
  return null;
5084
5564
  }
5085
5565
 
5566
+ if (newBreadcrumb.category === 'console') {
5567
+ return normalizeConsoleBreadcrumb(newBreadcrumb);
5568
+ }
5569
+
5086
5570
  return createBreadcrumb(newBreadcrumb);
5087
5571
  }
5088
5572
 
5573
+ /** exported for tests only */
5574
+ function normalizeConsoleBreadcrumb(breadcrumb) {
5575
+ const args = breadcrumb.data && breadcrumb.data.arguments;
5576
+
5577
+ if (!Array.isArray(args) || args.length === 0) {
5578
+ return createBreadcrumb(breadcrumb);
5579
+ }
5580
+
5581
+ let isTruncated = false;
5582
+
5583
+ // Avoid giant args captures
5584
+ const normalizedArgs = args.map(arg => {
5585
+ if (!arg) {
5586
+ return arg;
5587
+ }
5588
+ if (typeof arg === 'string') {
5589
+ if (arg.length > CONSOLE_ARG_MAX_SIZE) {
5590
+ isTruncated = true;
5591
+ return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;
5592
+ }
5593
+
5594
+ return arg;
5595
+ }
5596
+ if (typeof arg === 'object') {
5597
+ try {
5598
+ const normalizedArg = normalize(arg, 7);
5599
+ const stringified = JSON.stringify(normalizedArg);
5600
+ if (stringified.length > CONSOLE_ARG_MAX_SIZE) {
5601
+ const fixedJson = fixJson(stringified.slice(0, CONSOLE_ARG_MAX_SIZE));
5602
+ const json = JSON.parse(fixedJson);
5603
+ // We only set this after JSON.parse() was successfull, so we know we didn't run into `catch`
5604
+ isTruncated = true;
5605
+ return json;
5606
+ }
5607
+ return normalizedArg;
5608
+ } catch (e) {
5609
+ // fall back to default
5610
+ }
5611
+ }
5612
+
5613
+ return arg;
5614
+ });
5615
+
5616
+ return createBreadcrumb({
5617
+ ...breadcrumb,
5618
+ data: {
5619
+ ...breadcrumb.data,
5620
+ arguments: normalizedArgs,
5621
+ ...(isTruncated ? { _meta: { warnings: ['CONSOLE_ARG_TRUNCATED'] } } : {}),
5622
+ },
5623
+ });
5624
+ }
5625
+
5089
5626
  /**
5090
5627
  * Add global listeners that cannot be removed.
5091
5628
  */
@@ -5110,7 +5647,7 @@ function addGlobalListeners(replay) {
5110
5647
  client.on('afterSendEvent', handleAfterSendEvent(replay));
5111
5648
  client.on('createDsc', (dsc) => {
5112
5649
  const replayId = replay.getSessionId();
5113
- if (replayId) {
5650
+ if (replayId && replay.isEnabled()) {
5114
5651
  dsc.replay_id = replayId;
5115
5652
  }
5116
5653
  });
@@ -5418,7 +5955,7 @@ function getHandleRecordingEmit(replay) {
5418
5955
  // when an error occurs. Clear any state that happens before this current
5419
5956
  // checkout. This needs to happen before `addEvent()` which updates state
5420
5957
  // dependent on this reset.
5421
- if (replay.recordingMode === 'error' && isCheckout) {
5958
+ if (replay.recordingMode === 'buffer' && isCheckout) {
5422
5959
  replay.setInitialState();
5423
5960
  }
5424
5961
 
@@ -5444,7 +5981,7 @@ function getHandleRecordingEmit(replay) {
5444
5981
 
5445
5982
  // See note above re: session start needs to reflect the most recent
5446
5983
  // checkout.
5447
- if (replay.recordingMode === 'error' && replay.session) {
5984
+ if (replay.recordingMode === 'buffer' && replay.session) {
5448
5985
  const { earliestEvent } = replay.getContext();
5449
5986
  if (earliestEvent) {
5450
5987
  replay.session.started = earliestEvent;
@@ -5793,9 +6330,11 @@ class ReplayContainer {
5793
6330
  __init2() {this.performanceEvents = [];}
5794
6331
 
5795
6332
  /**
5796
- * Recording can happen in one of two modes:
5797
- * * session: Record the whole session, sending it continuously
5798
- * * error: Always keep the last 60s of recording, and when an error occurs, send it immediately
6333
+ * Recording can happen in one of three modes:
6334
+ * - session: Record the whole session, sending it continuously
6335
+ * - buffer: Always keep the last 60s of recording, requires:
6336
+ * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs
6337
+ * - or calling `flush()` to send the replay
5799
6338
  */
5800
6339
  __init3() {this.recordingMode = 'session';}
5801
6340
 
@@ -5804,7 +6343,8 @@ class ReplayContainer {
5804
6343
  * @hidden
5805
6344
  */
5806
6345
  __init4() {this.timeouts = {
5807
- sessionIdle: SESSION_IDLE_DURATION,
6346
+ sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,
6347
+ sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,
5808
6348
  maxSessionLife: MAX_SESSION_LIFE,
5809
6349
  }; }
5810
6350
 
@@ -5865,8 +6405,6 @@ class ReplayContainer {
5865
6405
  this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {
5866
6406
  maxWait: this._options.flushMaxDelay,
5867
6407
  });
5868
-
5869
- this._experimentalOptions = _getExperimentalOptions(options);
5870
6408
  }
5871
6409
 
5872
6410
  /** Get the event context. */
@@ -5890,58 +6428,102 @@ class ReplayContainer {
5890
6428
  }
5891
6429
 
5892
6430
  /**
5893
- * Get the experimental options.
5894
- * THIS IS INTERNAL AND SUBJECT TO CHANGE!
5895
- * @hidden
6431
+ * Initializes the plugin based on sampling configuration. Should not be
6432
+ * called outside of constructor.
5896
6433
  */
5897
- getExperimentalOptions() {
5898
- return this._experimentalOptions;
6434
+ initializeSampling() {
6435
+ const { errorSampleRate, sessionSampleRate } = this._options;
6436
+
6437
+ // If neither sample rate is > 0, then do nothing - user will need to call one of
6438
+ // `start()` or `startBuffering` themselves.
6439
+ if (errorSampleRate <= 0 && sessionSampleRate <= 0) {
6440
+ return;
6441
+ }
6442
+
6443
+ // Otherwise if there is _any_ sample rate set, try to load an existing
6444
+ // session, or create a new one.
6445
+ const isSessionSampled = this._loadAndCheckSession();
6446
+
6447
+ if (!isSessionSampled) {
6448
+ // This should only occur if `errorSampleRate` is 0 and was unsampled for
6449
+ // session-based replay. In this case there is nothing to do.
6450
+ return;
6451
+ }
6452
+
6453
+ if (!this.session) {
6454
+ // This should not happen, something wrong has occurred
6455
+ this._handleException(new Error('Unable to initialize and create session'));
6456
+ return;
6457
+ }
6458
+
6459
+ if (this.session.sampled && this.session.sampled !== 'session') {
6460
+ // If not sampled as session-based, then recording mode will be `buffer`
6461
+ // Note that we don't explicitly check if `sampled === 'buffer'` because we
6462
+ // could have sessions from Session storage that are still `error` from
6463
+ // prior SDK version.
6464
+ this.recordingMode = 'buffer';
6465
+ }
6466
+
6467
+ this._initializeRecording();
5899
6468
  }
5900
6469
 
5901
6470
  /**
5902
- * Initializes the plugin.
6471
+ * Start a replay regardless of sampling rate. Calling this will always
6472
+ * create a new session. Will throw an error if replay is already in progress.
5903
6473
  *
5904
6474
  * Creates or loads a session, attaches listeners to varying events (DOM,
5905
6475
  * _performanceObserver, Recording, Sentry SDK, etc)
5906
6476
  */
5907
6477
  start() {
5908
- this.setInitialState();
5909
-
5910
- if (!this._loadAndCheckSession()) {
5911
- return;
6478
+ if (this._isEnabled && this.recordingMode === 'session') {
6479
+ throw new Error('Replay recording is already in progress');
5912
6480
  }
5913
6481
 
5914
- // If there is no session, then something bad has happened - can't continue
5915
- if (!this.session) {
5916
- this._handleException(new Error('No session found'));
5917
- return;
6482
+ if (this._isEnabled && this.recordingMode === 'buffer') {
6483
+ throw new Error('Replay buffering is in progress, call `flush()` to save the replay');
5918
6484
  }
5919
6485
 
5920
- if (!this.session.sampled) {
5921
- // If session was not sampled, then we do not initialize the integration at all.
5922
- return;
5923
- }
6486
+ const previousSessionId = this.session && this.session.id;
5924
6487
 
5925
- // If session is sampled for errors, then we need to set the recordingMode
5926
- // to 'error', which will configure recording with different options.
5927
- if (this.session.sampled === 'error') {
5928
- this.recordingMode = 'error';
6488
+ const { session } = getSession({
6489
+ timeouts: this.timeouts,
6490
+ stickySession: Boolean(this._options.stickySession),
6491
+ currentSession: this.session,
6492
+ // This is intentional: create a new session-based replay when calling `start()`
6493
+ sessionSampleRate: 1,
6494
+ allowBuffering: false,
6495
+ });
6496
+
6497
+ session.previousSessionId = previousSessionId;
6498
+ this.session = session;
6499
+
6500
+ this._initializeRecording();
6501
+ }
6502
+
6503
+ /**
6504
+ * Start replay buffering. Buffers until `flush()` is called or, if
6505
+ * `replaysOnErrorSampleRate` > 0, an error occurs.
6506
+ */
6507
+ startBuffering() {
6508
+ if (this._isEnabled) {
6509
+ throw new Error('Replay recording is already in progress');
5929
6510
  }
5930
6511
 
5931
- // setup() is generally called on page load or manually - in both cases we
5932
- // should treat it as an activity
5933
- this._updateSessionActivity();
6512
+ const previousSessionId = this.session && this.session.id;
5934
6513
 
5935
- this.eventBuffer = createEventBuffer({
5936
- useCompression: this._options.useCompression,
6514
+ const { session } = getSession({
6515
+ timeouts: this.timeouts,
6516
+ stickySession: Boolean(this._options.stickySession),
6517
+ currentSession: this.session,
6518
+ sessionSampleRate: 0,
6519
+ allowBuffering: true,
5937
6520
  });
5938
6521
 
5939
- this._addListeners();
5940
-
5941
- // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout
5942
- this._isEnabled = true;
6522
+ session.previousSessionId = previousSessionId;
6523
+ this.session = session;
5943
6524
 
5944
- this.startRecording();
6525
+ this.recordingMode = 'buffer';
6526
+ this._initializeRecording();
5945
6527
  }
5946
6528
 
5947
6529
  /**
@@ -5956,7 +6538,7 @@ class ReplayContainer {
5956
6538
  // When running in error sampling mode, we need to overwrite `checkoutEveryNms`
5957
6539
  // Without this, it would record forever, until an error happens, which we don't want
5958
6540
  // instead, we'll always keep the last 60 seconds of replay before an error happened
5959
- ...(this.recordingMode === 'error' && { checkoutEveryNms: ERROR_CHECKOUT_TIME }),
6541
+ ...(this.recordingMode === 'buffer' && { checkoutEveryNms: BUFFER_CHECKOUT_TIME }),
5960
6542
  emit: getHandleRecordingEmit(this),
5961
6543
  onMutation: this._onMutationHandler,
5962
6544
  });
@@ -5967,17 +6549,18 @@ class ReplayContainer {
5967
6549
 
5968
6550
  /**
5969
6551
  * Stops the recording, if it was running.
5970
- * Returns true if it was stopped, else false.
6552
+ *
6553
+ * Returns true if it was previously stopped, or is now stopped,
6554
+ * otherwise false.
5971
6555
  */
5972
6556
  stopRecording() {
5973
6557
  try {
5974
6558
  if (this._stopRecording) {
5975
6559
  this._stopRecording();
5976
6560
  this._stopRecording = undefined;
5977
- return true;
5978
6561
  }
5979
6562
 
5980
- return false;
6563
+ return true;
5981
6564
  } catch (err) {
5982
6565
  this._handleException(err);
5983
6566
  return false;
@@ -5988,7 +6571,7 @@ class ReplayContainer {
5988
6571
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK
5989
6572
  * does not support a teardown
5990
6573
  */
5991
- stop(reason) {
6574
+ async stop(reason) {
5992
6575
  if (!this._isEnabled) {
5993
6576
  return;
5994
6577
  }
@@ -6004,12 +6587,24 @@ class ReplayContainer {
6004
6587
  log(msg);
6005
6588
  }
6006
6589
 
6590
+ // We can't move `_isEnabled` after awaiting a flush, otherwise we can
6591
+ // enter into an infinite loop when `stop()` is called while flushing.
6007
6592
  this._isEnabled = false;
6008
6593
  this._removeListeners();
6009
6594
  this.stopRecording();
6595
+
6596
+ this._debouncedFlush.cancel();
6597
+ // See comment above re: `_isEnabled`, we "force" a flush, ignoring the
6598
+ // `_isEnabled` state of the plugin since it was disabled above.
6599
+ await this._flush({ force: true });
6600
+
6601
+ // After flush, destroy event buffer
6010
6602
  this.eventBuffer && this.eventBuffer.destroy();
6011
6603
  this.eventBuffer = null;
6012
- this._debouncedFlush.cancel();
6604
+
6605
+ // Clear session from session storage, note this means if a new session
6606
+ // is started after, it will not have `previousSessionId`
6607
+ clearSession(this);
6013
6608
  } catch (err) {
6014
6609
  this._handleException(err);
6015
6610
  }
@@ -6040,6 +6635,45 @@ class ReplayContainer {
6040
6635
  this.startRecording();
6041
6636
  }
6042
6637
 
6638
+ /**
6639
+ * If not in "session" recording mode, flush event buffer which will create a new replay.
6640
+ * Unless `continueRecording` is false, the replay will continue to record and
6641
+ * behave as a "session"-based replay.
6642
+ *
6643
+ * Otherwise, queue up a flush.
6644
+ */
6645
+ async sendBufferedReplayOrFlush({ continueRecording = true } = {}) {
6646
+ if (this.recordingMode === 'session') {
6647
+ return this.flushImmediate();
6648
+ }
6649
+
6650
+ // Allow flush to complete before resuming as a session recording, otherwise
6651
+ // the checkout from `startRecording` may be included in the payload.
6652
+ // Prefer to keep the error replay as a separate (and smaller) segment
6653
+ // than the session replay.
6654
+ await this.flushImmediate();
6655
+
6656
+ const hasStoppedRecording = this.stopRecording();
6657
+
6658
+ if (!continueRecording || !hasStoppedRecording) {
6659
+ return;
6660
+ }
6661
+
6662
+ // Re-start recording, but in "session" recording mode
6663
+
6664
+ // Reset all "capture on error" configuration before
6665
+ // starting a new recording
6666
+ this.recordingMode = 'session';
6667
+
6668
+ // Once this session ends, we do not want to refresh it
6669
+ if (this.session) {
6670
+ this.session.shouldRefresh = false;
6671
+ this._maybeSaveSession();
6672
+ }
6673
+
6674
+ this.startRecording();
6675
+ }
6676
+
6043
6677
  /**
6044
6678
  * We want to batch uploads of replay events. Save events only if
6045
6679
  * `<flushMinDelay>` milliseconds have elapsed since the last event
@@ -6049,12 +6683,12 @@ class ReplayContainer {
6049
6683
  * processing and hand back control to caller.
6050
6684
  */
6051
6685
  addUpdate(cb) {
6052
- // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'error'`)
6686
+ // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)
6053
6687
  const cbResult = cb();
6054
6688
 
6055
6689
  // If this option is turned on then we will only want to call `flush`
6056
6690
  // explicitly
6057
- if (this.recordingMode === 'error') {
6691
+ if (this.recordingMode === 'buffer') {
6058
6692
  return;
6059
6693
  }
6060
6694
 
@@ -6126,12 +6760,12 @@ class ReplayContainer {
6126
6760
  const oldSessionId = this.getSessionId();
6127
6761
 
6128
6762
  // Prevent starting a new session if the last user activity is older than
6129
- // SESSION_IDLE_DURATION. Otherwise non-user activity can trigger a new
6763
+ // SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new
6130
6764
  // session+recording. This creates noisy replays that do not have much
6131
6765
  // content in them.
6132
6766
  if (
6133
6767
  this._lastActivity &&
6134
- isExpired(this._lastActivity, this.timeouts.sessionIdle) &&
6768
+ isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&
6135
6769
  this.session &&
6136
6770
  this.session.sampled === 'session'
6137
6771
  ) {
@@ -6181,6 +6815,30 @@ class ReplayContainer {
6181
6815
  this._context.urls.push(url);
6182
6816
  }
6183
6817
 
6818
+ /**
6819
+ * Initialize and start all listeners to varying events (DOM,
6820
+ * Performance Observer, Recording, Sentry SDK, etc)
6821
+ */
6822
+ _initializeRecording() {
6823
+ this.setInitialState();
6824
+
6825
+ // this method is generally called on page load or manually - in both cases
6826
+ // we should treat it as an activity
6827
+ this._updateSessionActivity();
6828
+
6829
+ this.eventBuffer = createEventBuffer({
6830
+ useCompression: this._options.useCompression,
6831
+ });
6832
+
6833
+ this._removeListeners();
6834
+ this._addListeners();
6835
+
6836
+ // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout
6837
+ this._isEnabled = true;
6838
+
6839
+ this.startRecording();
6840
+ }
6841
+
6184
6842
  /** A wrapper to conditionally capture exceptions. */
6185
6843
  _handleException(error) {
6186
6844
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay]', error);
@@ -6200,7 +6858,7 @@ class ReplayContainer {
6200
6858
  stickySession: Boolean(this._options.stickySession),
6201
6859
  currentSession: this.session,
6202
6860
  sessionSampleRate: this._options.sessionSampleRate,
6203
- errorSampleRate: this._options.errorSampleRate,
6861
+ allowBuffering: this._options.errorSampleRate > 0,
6204
6862
  });
6205
6863
 
6206
6864
  // If session was newly created (i.e. was not loaded from storage), then
@@ -6217,7 +6875,7 @@ class ReplayContainer {
6217
6875
  this.session = session;
6218
6876
 
6219
6877
  if (!this.session.sampled) {
6220
- this.stop('session unsampled');
6878
+ void this.stop('session unsampled');
6221
6879
  return false;
6222
6880
  }
6223
6881
 
@@ -6341,7 +6999,7 @@ class ReplayContainer {
6341
6999
  const isSessionActive = this.checkAndHandleExpiredSession();
6342
7000
 
6343
7001
  if (!isSessionActive) {
6344
- // If the user has come back to the page within SESSION_IDLE_DURATION
7002
+ // If the user has come back to the page within SESSION_IDLE_PAUSE_DURATION
6345
7003
  // ms, we will re-use the existing session, otherwise create a new
6346
7004
  // session
6347
7005
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Document has become active, but session has expired');
@@ -6415,7 +7073,7 @@ class ReplayContainer {
6415
7073
  * Only flush if `this.recordingMode === 'session'`
6416
7074
  */
6417
7075
  _conditionalFlush() {
6418
- if (this.recordingMode === 'error') {
7076
+ if (this.recordingMode === 'buffer') {
6419
7077
  return;
6420
7078
  }
6421
7079
 
@@ -6510,7 +7168,7 @@ class ReplayContainer {
6510
7168
  // This means we retried 3 times and all of them failed,
6511
7169
  // or we ran into a problem we don't want to retry, like rate limiting.
6512
7170
  // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments
6513
- this.stop('sendReplay');
7171
+ void this.stop('sendReplay');
6514
7172
 
6515
7173
  const client = getCurrentHub().getClient();
6516
7174
 
@@ -6524,8 +7182,12 @@ class ReplayContainer {
6524
7182
  * Flush recording data to Sentry. Creates a lock so that only a single flush
6525
7183
  * can be active at a time. Do not call this directly.
6526
7184
  */
6527
- __init16() {this._flush = async () => {
6528
- if (!this._isEnabled) {
7185
+ __init16() {this._flush = async ({
7186
+ force = false,
7187
+ }
7188
+
7189
+ = {}) => {
7190
+ if (!this._isEnabled && !force) {
6529
7191
  // This can happen if e.g. the replay was stopped because of exceeding the retry limit
6530
7192
  return;
6531
7193
  }
@@ -6606,23 +7268,6 @@ class ReplayContainer {
6606
7268
  };}
6607
7269
  }
6608
7270
 
6609
- function _getExperimentalOptions(options) {
6610
- const requestHeaders = options._experiments.captureRequestHeaders || [];
6611
- const responseHeaders = options._experiments.captureResponseHeaders || [];
6612
- const captureBodies = options._experiments.captureNetworkBodies || false;
6613
-
6614
- // Add defaults
6615
- const defaultHeaders = ['content-length', 'content-type', 'accept'];
6616
-
6617
- return {
6618
- network: {
6619
- captureBodies,
6620
- requestHeaders: [...defaultHeaders, ...requestHeaders.map(header => header.toLowerCase())],
6621
- responseHeaders: [...defaultHeaders, ...responseHeaders.map(header => header.toLowerCase())],
6622
- },
6623
- };
6624
- }
6625
-
6626
7271
  function getOption(
6627
7272
  selectors,
6628
7273
  defaultSelectors,
@@ -6726,6 +7371,8 @@ function isElectronNodeRenderer() {
6726
7371
  const MEDIA_SELECTORS =
6727
7372
  'img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]';
6728
7373
 
7374
+ const DEFAULT_NETWORK_HEADERS = ['content-length', 'content-type', 'accept'];
7375
+
6729
7376
  let _initialized = false;
6730
7377
 
6731
7378
  /**
@@ -6766,6 +7413,11 @@ class Replay {
6766
7413
  maskAllInputs = true,
6767
7414
  blockAllMedia = true,
6768
7415
 
7416
+ networkDetailAllowUrls = [],
7417
+ networkCaptureBodies = true,
7418
+ networkRequestHeaders = [],
7419
+ networkResponseHeaders = [],
7420
+
6769
7421
  mask = [],
6770
7422
  unmask = [],
6771
7423
  block = [],
@@ -6824,6 +7476,11 @@ class Replay {
6824
7476
  errorSampleRate,
6825
7477
  useCompression,
6826
7478
  blockAllMedia,
7479
+ networkDetailAllowUrls,
7480
+ networkCaptureBodies,
7481
+ networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),
7482
+ networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),
7483
+
6827
7484
  _experiments,
6828
7485
  };
6829
7486
 
@@ -6877,14 +7534,7 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
6877
7534
  }
6878
7535
 
6879
7536
  /**
6880
- * We previously used to create a transaction in `setupOnce` and it would
6881
- * potentially create a transaction before some native SDK integrations have run
6882
- * and applied their own global event processor. An example is:
6883
- * https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
6884
- *
6885
- * So we call `replay.setup` in next event loop as a workaround to wait for other
6886
- * global event processors to finish. This is no longer needed, but keeping it
6887
- * here to avoid any future issues.
7537
+ * Setup and initialize replay container
6888
7538
  */
6889
7539
  setupOnce() {
6890
7540
  if (!isBrowser()) {
@@ -6893,12 +7543,20 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
6893
7543
 
6894
7544
  this._setup();
6895
7545
 
6896
- // XXX: See method comments above
6897
- setTimeout(() => this.start());
7546
+ // Once upon a time, we tried to create a transaction in `setupOnce` and it would
7547
+ // potentially create a transaction before some native SDK integrations have run
7548
+ // and applied their own global event processor. An example is:
7549
+ // https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
7550
+ //
7551
+ // So we call `this._initialize()` in next event loop as a workaround to wait for other
7552
+ // global event processors to finish. This is no longer needed, but keeping it
7553
+ // here to avoid any future issues.
7554
+ setTimeout(() => this._initialize());
6898
7555
  }
6899
7556
 
6900
7557
  /**
6901
- * Initializes the plugin.
7558
+ * Start a replay regardless of sampling rate. Calling this will always
7559
+ * create a new session. Will throw an error if replay is already in progress.
6902
7560
  *
6903
7561
  * Creates or loads a session, attaches listeners to varying events (DOM,
6904
7562
  * PerformanceObserver, Recording, Sentry SDK, etc)
@@ -6911,27 +7569,43 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
6911
7569
  this._replay.start();
6912
7570
  }
6913
7571
 
7572
+ /**
7573
+ * Start replay buffering. Buffers until `flush()` is called or, if
7574
+ * `replaysOnErrorSampleRate` > 0, until an error occurs.
7575
+ */
7576
+ startBuffering() {
7577
+ if (!this._replay) {
7578
+ return;
7579
+ }
7580
+
7581
+ this._replay.startBuffering();
7582
+ }
7583
+
6914
7584
  /**
6915
7585
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK
6916
7586
  * does not support a teardown
6917
7587
  */
6918
7588
  stop() {
6919
7589
  if (!this._replay) {
6920
- return;
7590
+ return Promise.resolve();
6921
7591
  }
6922
7592
 
6923
- this._replay.stop();
7593
+ return this._replay.stop();
6924
7594
  }
6925
7595
 
6926
7596
  /**
6927
- * Immediately send all pending events.
7597
+ * If not in "session" recording mode, flush event buffer which will create a new replay.
7598
+ * Unless `continueRecording` is false, the replay will continue to record and
7599
+ * behave as a "session"-based replay.
7600
+ *
7601
+ * Otherwise, queue up a flush.
6928
7602
  */
6929
- flush() {
7603
+ flush(options) {
6930
7604
  if (!this._replay || !this._replay.isEnabled()) {
6931
- return;
7605
+ return Promise.resolve();
6932
7606
  }
6933
7607
 
6934
- return this._replay.flushImmediate();
7608
+ return this._replay.sendBufferedReplayOrFlush(options);
6935
7609
  }
6936
7610
 
6937
7611
  /**
@@ -6944,6 +7618,16 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
6944
7618
 
6945
7619
  return this._replay.getSessionId();
6946
7620
  }
7621
+ /**
7622
+ * Initializes replay.
7623
+ */
7624
+ _initialize() {
7625
+ if (!this._replay) {
7626
+ return;
7627
+ }
7628
+
7629
+ this._replay.initializeSampling();
7630
+ }
6947
7631
 
6948
7632
  /** Setup the integration. */
6949
7633
  _setup() {
@@ -6993,5 +7677,9 @@ function loadReplayOptionsFromClient(initialOptions) {
6993
7677
  return finalOptions;
6994
7678
  }
6995
7679
 
7680
+ function _getMergedNetworkHeaders(headers) {
7681
+ return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];
7682
+ }
7683
+
6996
7684
  export { Replay };
6997
7685
  //# sourceMappingURL=index.js.map