@sentry/replay 7.43.0 → 7.44.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.
package/cjs/index.js CHANGED
@@ -31,7 +31,7 @@ const ERROR_CHECKOUT_TIME = 60000;
31
31
  const RETRY_BASE_INTERVAL = 5000;
32
32
  const RETRY_MAX_COUNT = 3;
33
33
 
34
- var NodeType;
34
+ var NodeType$1;
35
35
  (function (NodeType) {
36
36
  NodeType[NodeType["Document"] = 0] = "Document";
37
37
  NodeType[NodeType["DocumentType"] = 1] = "DocumentType";
@@ -39,7 +39,7 @@ var NodeType;
39
39
  NodeType[NodeType["Text"] = 3] = "Text";
40
40
  NodeType[NodeType["CDATA"] = 4] = "CDATA";
41
41
  NodeType[NodeType["Comment"] = 5] = "Comment";
42
- })(NodeType || (NodeType = {}));
42
+ })(NodeType$1 || (NodeType$1 = {}));
43
43
 
44
44
  function isElement(n) {
45
45
  return n.nodeType === n.ELEMENT_NODE;
@@ -49,8 +49,13 @@ function isShadowRoot(n) {
49
49
  return Boolean(host && host.shadowRoot && host.shadowRoot === n);
50
50
  }
51
51
  function isInputTypeMasked({ maskInputOptions, tagName, type, }) {
52
+ if (tagName.toLowerCase() === 'option') {
53
+ tagName = 'select';
54
+ }
55
+ const actualType = typeof type === 'string' ? type.toLowerCase() : undefined;
52
56
  return (maskInputOptions[tagName.toLowerCase()] ||
53
- maskInputOptions[type] ||
57
+ (actualType && maskInputOptions[actualType]) ||
58
+ actualType === 'password' ||
54
59
  (tagName === 'input' && !type && maskInputOptions['text']));
55
60
  }
56
61
  function hasInputMaskOptions({ tagName, type, maskInputOptions, maskInputSelector, }) {
@@ -61,6 +66,9 @@ function maskInputValue({ input, maskInputSelector, unmaskInputSelector, maskInp
61
66
  if (unmaskInputSelector && input.matches(unmaskInputSelector)) {
62
67
  return text;
63
68
  }
69
+ if (input.hasAttribute('rr_is_password')) {
70
+ type = 'password';
71
+ }
64
72
  if (isInputTypeMasked({ maskInputOptions, tagName, type }) ||
65
73
  (maskInputSelector && input.matches(maskInputSelector))) {
66
74
  if (maskInputFn) {
@@ -266,10 +274,12 @@ function getHref() {
266
274
  a.href = '';
267
275
  return a.href;
268
276
  }
269
- function transformAttribute(doc, element, tagName, name, value, maskAllText, maskTextFn) {
277
+ function transformAttribute(doc, element, _tagName, _name, value, maskAllText, unmaskTextSelector, maskTextFn) {
270
278
  if (!value) {
271
279
  return value;
272
280
  }
281
+ const name = _name.toLowerCase();
282
+ const tagName = _tagName.toLowerCase();
273
283
  if (name === 'src' || name === 'href') {
274
284
  return absoluteToDoc(doc, value);
275
285
  }
@@ -290,15 +300,21 @@ function transformAttribute(doc, element, tagName, name, value, maskAllText, mas
290
300
  return absoluteToDoc(doc, value);
291
301
  }
292
302
  else if (maskAllText &&
293
- (['placeholder', 'title', 'aria-label'].indexOf(name) > -1 ||
294
- (tagName === 'input' &&
295
- name === 'value' &&
296
- element.getAttribute('type') &&
297
- ['submit', 'button'].indexOf(element.getAttribute('type').toLowerCase()) > -1))) {
303
+ _shouldMaskAttribute(element, name, tagName, unmaskTextSelector)) {
298
304
  return maskTextFn ? maskTextFn(value) : defaultMaskFn(value);
299
305
  }
300
306
  return value;
301
307
  }
308
+ function _shouldMaskAttribute(element, attribute, tagName, unmaskTextSelector) {
309
+ if (unmaskTextSelector && element.matches(unmaskTextSelector)) {
310
+ return false;
311
+ }
312
+ return (['placeholder', 'title', 'aria-label'].indexOf(attribute) > -1 ||
313
+ (tagName === 'input' &&
314
+ attribute === 'value' &&
315
+ element.hasAttribute('type') &&
316
+ ['submit', 'button'].indexOf(element.getAttribute('type').toLowerCase()) > -1));
317
+ }
302
318
  function _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {
303
319
  if (unblockSelector && element.matches(unblockSelector)) {
304
320
  return false;
@@ -405,7 +421,7 @@ function serializeNode(n, options) {
405
421
  case n.DOCUMENT_NODE:
406
422
  if (n.compatMode !== 'CSS1Compat') {
407
423
  return {
408
- type: NodeType.Document,
424
+ type: NodeType$1.Document,
409
425
  childNodes: [],
410
426
  compatMode: n.compatMode,
411
427
  rootId,
@@ -413,14 +429,14 @@ function serializeNode(n, options) {
413
429
  }
414
430
  else {
415
431
  return {
416
- type: NodeType.Document,
432
+ type: NodeType$1.Document,
417
433
  childNodes: [],
418
434
  rootId,
419
435
  };
420
436
  }
421
437
  case n.DOCUMENT_TYPE_NODE:
422
438
  return {
423
- type: NodeType.DocumentType,
439
+ type: NodeType$1.DocumentType,
424
440
  name: n.name,
425
441
  publicId: n.publicId,
426
442
  systemId: n.systemId,
@@ -432,7 +448,7 @@ function serializeNode(n, options) {
432
448
  let attributes = {};
433
449
  for (const { name, value } of Array.from(n.attributes)) {
434
450
  if (!skipAttribute(tagName, name)) {
435
- attributes[name] = transformAttribute(doc, n, tagName, name, value, maskAllText, maskTextFn);
451
+ attributes[name] = transformAttribute(doc, n, tagName, name, value, maskAllText, unmaskTextSelector, maskTextFn);
436
452
  }
437
453
  }
438
454
  if (tagName === 'link' && inlineStylesheet) {
@@ -461,15 +477,16 @@ function serializeNode(n, options) {
461
477
  }
462
478
  if (tagName === 'input' ||
463
479
  tagName === 'textarea' ||
464
- tagName === 'select') {
465
- const value = n.value;
466
- if (attributes.type !== 'radio' &&
467
- attributes.type !== 'checkbox' &&
468
- attributes.type !== 'submit' &&
480
+ tagName === 'select' ||
481
+ tagName === 'option') {
482
+ const el = n;
483
+ const value = getInputValue(tagName, el, attributes);
484
+ const checked = n.checked;
485
+ if (attributes.type !== 'submit' &&
469
486
  attributes.type !== 'button' &&
470
487
  value) {
471
488
  attributes.value = maskInputValue({
472
- input: n,
489
+ input: el,
473
490
  type: attributes.type,
474
491
  tagName,
475
492
  value,
@@ -479,8 +496,8 @@ function serializeNode(n, options) {
479
496
  maskInputFn,
480
497
  });
481
498
  }
482
- else if (n.checked) {
483
- attributes.checked = n.checked;
499
+ if (checked) {
500
+ attributes.checked = checked;
484
501
  }
485
502
  }
486
503
  if (tagName === 'option') {
@@ -562,7 +579,7 @@ function serializeNode(n, options) {
562
579
  delete attributes.src;
563
580
  }
564
581
  return {
565
- type: NodeType.Element,
582
+ type: NodeType$1.Element,
566
583
  tagName,
567
584
  attributes,
568
585
  childNodes: [],
@@ -594,6 +611,19 @@ function serializeNode(n, options) {
594
611
  if (parentTagName === 'TEXTAREA' && textContent) {
595
612
  textContent = '';
596
613
  }
614
+ else if (parentTagName === 'OPTION' && textContent) {
615
+ const option = n.parentNode;
616
+ textContent = maskInputValue({
617
+ input: option,
618
+ type: null,
619
+ tagName: parentTagName,
620
+ value: textContent,
621
+ maskInputSelector,
622
+ unmaskInputSelector,
623
+ maskInputOptions,
624
+ maskInputFn,
625
+ });
626
+ }
597
627
  else if (!isStyle &&
598
628
  !isScript &&
599
629
  needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText) &&
@@ -603,20 +633,20 @@ function serializeNode(n, options) {
603
633
  : defaultMaskFn(textContent);
604
634
  }
605
635
  return {
606
- type: NodeType.Text,
636
+ type: NodeType$1.Text,
607
637
  textContent: textContent || '',
608
638
  isStyle,
609
639
  rootId,
610
640
  };
611
641
  case n.CDATA_SECTION_NODE:
612
642
  return {
613
- type: NodeType.CDATA,
643
+ type: NodeType$1.CDATA,
614
644
  textContent: '',
615
645
  rootId,
616
646
  };
617
647
  case n.COMMENT_NODE:
618
648
  return {
619
- type: NodeType.Comment,
649
+ type: NodeType$1.Comment,
620
650
  textContent: n.textContent || '',
621
651
  rootId,
622
652
  };
@@ -633,10 +663,10 @@ function lowerIfExists(maybeAttr) {
633
663
  }
634
664
  }
635
665
  function slimDOMExcluded(sn, slimDOMOptions) {
636
- if (slimDOMOptions.comment && sn.type === NodeType.Comment) {
666
+ if (slimDOMOptions.comment && sn.type === NodeType$1.Comment) {
637
667
  return true;
638
668
  }
639
- else if (sn.type === NodeType.Element) {
669
+ else if (sn.type === NodeType$1.Element) {
640
670
  if (slimDOMOptions.script &&
641
671
  (sn.tagName === 'script' ||
642
672
  (sn.tagName === 'link' &&
@@ -737,7 +767,7 @@ function serializeNodeWithId(n, options) {
737
767
  }
738
768
  else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||
739
769
  (!preserveWhiteSpace &&
740
- _serializedNode.type === NodeType.Text &&
770
+ _serializedNode.type === NodeType$1.Text &&
741
771
  !_serializedNode.isStyle &&
742
772
  !_serializedNode.textContent.replace(/^\s+|\s+$/gm, '').length)) {
743
773
  id = IGNORED_NODE;
@@ -755,17 +785,17 @@ function serializeNodeWithId(n, options) {
755
785
  onSerialize(n);
756
786
  }
757
787
  let recordChild = !skipChild;
758
- if (serializedNode.type === NodeType.Element) {
788
+ if (serializedNode.type === NodeType$1.Element) {
759
789
  recordChild = recordChild && !serializedNode.needBlock;
760
790
  delete serializedNode.needBlock;
761
791
  if (n.shadowRoot)
762
792
  serializedNode.isShadowHost = true;
763
793
  }
764
- if ((serializedNode.type === NodeType.Document ||
765
- serializedNode.type === NodeType.Element) &&
794
+ if ((serializedNode.type === NodeType$1.Document ||
795
+ serializedNode.type === NodeType$1.Element) &&
766
796
  recordChild) {
767
797
  if (slimDOMOptions.headWhitespace &&
768
- _serializedNode.type === NodeType.Element &&
798
+ _serializedNode.type === NodeType$1.Element &&
769
799
  _serializedNode.tagName === 'head') {
770
800
  preserveWhiteSpace = false;
771
801
  }
@@ -815,7 +845,7 @@ function serializeNodeWithId(n, options) {
815
845
  if (n.parentNode && isShadowRoot(n.parentNode)) {
816
846
  serializedNode.isShadow = true;
817
847
  }
818
- if (serializedNode.type === NodeType.Element &&
848
+ if (serializedNode.type === NodeType$1.Element &&
819
849
  serializedNode.tagName === 'iframe') {
820
850
  onceIframeLoaded(n, () => {
821
851
  const iframeDoc = n.contentDocument;
@@ -875,12 +905,9 @@ function snapshot(n, options) {
875
905
  week: true,
876
906
  textarea: true,
877
907
  select: true,
878
- password: true,
879
908
  }
880
909
  : maskAllInputs === false
881
- ? {
882
- password: true,
883
- }
910
+ ? {}
884
911
  : maskAllInputs;
885
912
  const slimDOMOptions = slimDOM === true || slimDOM === 'all'
886
913
  ?
@@ -933,6 +960,13 @@ function snapshot(n, options) {
933
960
  function skipAttribute(tagName, attributeName, value) {
934
961
  return ((tagName === 'video' || tagName === 'audio') && attributeName === 'autoplay');
935
962
  }
963
+ function getInputValue(tagName, el, attributes) {
964
+ if (tagName === 'input' &&
965
+ (attributes.type === 'radio' || attributes.type === 'checkbox')) {
966
+ return el.getAttribute('value') || '';
967
+ }
968
+ return el.value;
969
+ }
936
970
 
937
971
  var EventType;
938
972
  (function (EventType) {
@@ -1243,7 +1277,7 @@ function polyfill(win = window) {
1243
1277
  }
1244
1278
  function isIframeINode(node) {
1245
1279
  if ('__sn' in node) {
1246
- return (node.__sn.type === NodeType.Element && node.__sn.tagName === 'iframe');
1280
+ return (node.__sn.type === NodeType$1.Element && node.__sn.tagName === 'iframe');
1247
1281
  }
1248
1282
  return false;
1249
1283
  }
@@ -1533,15 +1567,15 @@ class MutationBuffer {
1533
1567
  }
1534
1568
  case 'attributes': {
1535
1569
  const target = m.target;
1536
- let value = m.target.getAttribute(m.attributeName);
1570
+ let value = target.getAttribute(m.attributeName);
1537
1571
  if (m.attributeName === 'value') {
1538
1572
  value = maskInputValue({
1539
1573
  input: target,
1540
1574
  maskInputSelector: this.maskInputSelector,
1541
1575
  unmaskInputSelector: this.unmaskInputSelector,
1542
1576
  maskInputOptions: this.maskInputOptions,
1543
- tagName: m.target.tagName,
1544
- type: m.target.getAttribute('type'),
1577
+ tagName: target.tagName,
1578
+ type: target.getAttribute('type'),
1545
1579
  value,
1546
1580
  maskInputFn: this.maskInputFn,
1547
1581
  });
@@ -1557,6 +1591,11 @@ class MutationBuffer {
1557
1591
  };
1558
1592
  this.attributes.push(item);
1559
1593
  }
1594
+ if (m.attributeName === 'type' &&
1595
+ m.target.tagName === 'INPUT' &&
1596
+ (m.oldValue || '').toLowerCase() === 'password') {
1597
+ m.target.setAttribute('rr_is_password', 'true');
1598
+ }
1560
1599
  if (m.attributeName === 'style') {
1561
1600
  const old = this.doc.createElement('span');
1562
1601
  if (m.oldValue) {
@@ -1593,7 +1632,7 @@ class MutationBuffer {
1593
1632
  }
1594
1633
  else {
1595
1634
  const element = m.target;
1596
- item.attributes[m.attributeName] = transformAttribute(this.doc, element, element.tagName, m.attributeName, value, this.maskAllText, this.maskTextFn);
1635
+ item.attributes[m.attributeName] = transformAttribute(this.doc, element, element.tagName, m.attributeName, value, this.maskAllText, this.unmaskTextSelector, this.maskTextFn);
1597
1636
  }
1598
1637
  break;
1599
1638
  }
@@ -1891,7 +1930,8 @@ function initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockCl
1891
1930
  function initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {
1892
1931
  const updatePosition = throttle((evt) => {
1893
1932
  const target = getEventTarget(evt);
1894
- if (!target || isBlocked(target, blockClass, blockSelector, unblockSelector)) {
1933
+ if (!target ||
1934
+ isBlocked(target, blockClass, blockSelector, unblockSelector)) {
1895
1935
  return;
1896
1936
  }
1897
1937
  const id = mirror.getId(target);
@@ -1941,29 +1981,33 @@ const lastInputValueMap = new WeakMap();
1941
1981
  function initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, unblockSelector, ignoreClass, ignoreSelector, maskInputSelector, unmaskInputSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, }) {
1942
1982
  function eventHandler(event) {
1943
1983
  let target = getEventTarget(event);
1984
+ const tagName = target && target.tagName;
1944
1985
  const userTriggered = event.isTrusted;
1945
- if (target && target.tagName === 'OPTION')
1986
+ if (tagName === 'OPTION')
1946
1987
  target = target.parentElement;
1947
1988
  if (!target ||
1948
- !target.tagName ||
1949
- INPUT_TAGS.indexOf(target.tagName) < 0 ||
1989
+ !tagName ||
1990
+ INPUT_TAGS.indexOf(tagName) < 0 ||
1950
1991
  isBlocked(target, blockClass, blockSelector, unblockSelector)) {
1951
1992
  return;
1952
1993
  }
1953
- const type = target.type;
1994
+ let type = target.type;
1954
1995
  if (target.classList.contains(ignoreClass) ||
1955
1996
  (ignoreSelector && target.matches(ignoreSelector))) {
1956
1997
  return;
1957
1998
  }
1958
1999
  let text = target.value;
1959
2000
  let isChecked = false;
2001
+ if (target.hasAttribute('rr_is_password')) {
2002
+ type = 'password';
2003
+ }
1960
2004
  if (type === 'radio' || type === 'checkbox') {
1961
2005
  isChecked = target.checked;
1962
2006
  }
1963
2007
  else if (hasInputMaskOptions({
1964
2008
  maskInputOptions,
1965
2009
  maskInputSelector,
1966
- tagName: target.tagName,
2010
+ tagName,
1967
2011
  type,
1968
2012
  })) {
1969
2013
  text = maskInputValue({
@@ -1971,7 +2015,7 @@ function initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, un
1971
2015
  maskInputOptions,
1972
2016
  maskInputSelector,
1973
2017
  unmaskInputSelector,
1974
- tagName: target.tagName,
2018
+ tagName,
1975
2019
  type,
1976
2020
  value: text,
1977
2021
  maskInputFn,
@@ -2195,7 +2239,8 @@ function initStyleDeclarationObserver({ styleDeclarationCb, mirror }, { win }) {
2195
2239
  function initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, unblockSelector, mirror, sampling, }) {
2196
2240
  const handler = (type) => throttle(callbackWrapper((event) => {
2197
2241
  const target = getEventTarget(event);
2198
- if (!target || isBlocked(target, blockClass, blockSelector, unblockSelector)) {
2242
+ if (!target ||
2243
+ isBlocked(target, blockClass, blockSelector, unblockSelector)) {
2199
2244
  return;
2200
2245
  }
2201
2246
  const { currentTime, volume, muted } = target;
@@ -2858,11 +2903,12 @@ function record(options = {}) {
2858
2903
  week: true,
2859
2904
  textarea: true,
2860
2905
  select: true,
2861
- password: true,
2906
+ radio: true,
2907
+ checkbox: true,
2862
2908
  }
2863
2909
  : _maskInputOptions !== undefined
2864
2910
  ? _maskInputOptions
2865
- : { password: true };
2911
+ : {};
2866
2912
  const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'
2867
2913
  ? {
2868
2914
  script: true,
@@ -3719,7 +3765,7 @@ function isSampled(sampleRate) {
3719
3765
  * Get a session with defaults & applied sampling.
3720
3766
  */
3721
3767
  function makeSession(session) {
3722
- const now = new Date().getTime();
3768
+ const now = Date.now();
3723
3769
  const id = session.id || utils.uuid4();
3724
3770
  // Note that this means we cannot set a started/lastActivity of `0`, but this should not be relevant outside of tests.
3725
3771
  const started = session.started || now;
@@ -3857,7 +3903,7 @@ async function addEvent(
3857
3903
  // page has been left open and idle for a long period of time and user
3858
3904
  // comes back to trigger a new session. The performance entries rely on
3859
3905
  // `performance.timeOrigin`, which is when the page first opened.
3860
- if (timestampInMs + replay.timeouts.sessionIdle < new Date().getTime()) {
3906
+ if (timestampInMs + replay.timeouts.sessionIdle < Date.now()) {
3861
3907
  return null;
3862
3908
  }
3863
3909
 
@@ -3882,6 +3928,111 @@ async function addEvent(
3882
3928
  }
3883
3929
  }
3884
3930
 
3931
+ /** If the event is an error event */
3932
+ function isErrorEvent(event) {
3933
+ return !event.type;
3934
+ }
3935
+
3936
+ /** If the event is a transaction event */
3937
+ function isTransactionEvent(event) {
3938
+ return event.type === 'transaction';
3939
+ }
3940
+
3941
+ /** If the event is an replay event */
3942
+ function isReplayEvent(event) {
3943
+ return event.type === 'replay_event';
3944
+ }
3945
+
3946
+ /**
3947
+ * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.
3948
+ */
3949
+ function handleAfterSendEvent(replay) {
3950
+ // Custom transports may still be returning `Promise<void>`, which means we cannot expect the status code to be available there
3951
+ // TODO (v8): remove this check as it will no longer be necessary
3952
+ const enforceStatusCode = isBaseTransportSend();
3953
+
3954
+ return (event, sendResponse) => {
3955
+ if (!isErrorEvent(event) && !isTransactionEvent(event)) {
3956
+ return;
3957
+ }
3958
+
3959
+ const statusCode = sendResponse && sendResponse.statusCode;
3960
+
3961
+ // We only want to do stuff on successful error sending, otherwise you get error replays without errors attached
3962
+ // If not using the base transport, we allow `undefined` response (as a custom transport may not implement this correctly yet)
3963
+ // If we do use the base transport, we skip if we encountered an non-OK status code
3964
+ if (enforceStatusCode && (!statusCode || statusCode < 200 || statusCode >= 300)) {
3965
+ return;
3966
+ }
3967
+
3968
+ // Collect traceIds in _context regardless of `recordingMode`
3969
+ // In error mode, _context gets cleared on every checkout
3970
+ if (isTransactionEvent(event) && event.contexts && event.contexts.trace && event.contexts.trace.trace_id) {
3971
+ replay.getContext().traceIds.add(event.contexts.trace.trace_id );
3972
+ return;
3973
+ }
3974
+
3975
+ // Everything below is just for error events
3976
+ if (!isErrorEvent(event)) {
3977
+ return;
3978
+ }
3979
+
3980
+ // Add error to list of errorIds of replay
3981
+ if (event.event_id) {
3982
+ replay.getContext().errorIds.add(event.event_id);
3983
+ }
3984
+
3985
+ // Trigger error recording
3986
+ // Need to be very careful that this does not cause an infinite loop
3987
+ if (
3988
+ replay.recordingMode === 'error' &&
3989
+ event.exception &&
3990
+ event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because otherwise we could loop indefinitely with trying to capture replay and failing
3991
+ ) {
3992
+ setTimeout(async () => {
3993
+ // Allow flush to complete before resuming as a session recording, otherwise
3994
+ // the checkout from `startRecording` may be included in the payload.
3995
+ // Prefer to keep the error replay as a separate (and smaller) segment
3996
+ // than the session replay.
3997
+ await replay.flushImmediate();
3998
+
3999
+ if (replay.stopRecording()) {
4000
+ // Reset all "capture on error" configuration before
4001
+ // starting a new recording
4002
+ replay.recordingMode = 'session';
4003
+ replay.startRecording();
4004
+ }
4005
+ });
4006
+ }
4007
+ };
4008
+ }
4009
+
4010
+ function isBaseTransportSend() {
4011
+ const client = core.getCurrentHub().getClient();
4012
+ if (!client) {
4013
+ return false;
4014
+ }
4015
+
4016
+ const transport = client.getTransport();
4017
+ if (!transport) {
4018
+ return false;
4019
+ }
4020
+
4021
+ return (
4022
+ (transport.send ).__sentry__baseTransport__ || false
4023
+ );
4024
+ }
4025
+
4026
+ var NodeType;
4027
+ (function (NodeType) {
4028
+ NodeType[NodeType["Document"] = 0] = "Document";
4029
+ NodeType[NodeType["DocumentType"] = 1] = "DocumentType";
4030
+ NodeType[NodeType["Element"] = 2] = "Element";
4031
+ NodeType[NodeType["Text"] = 3] = "Text";
4032
+ NodeType[NodeType["CDATA"] = 4] = "CDATA";
4033
+ NodeType[NodeType["Comment"] = 5] = "Comment";
4034
+ })(NodeType || (NodeType = {}));
4035
+
3885
4036
  /**
3886
4037
  * Create a breadcrumb for a replay.
3887
4038
  */
@@ -3889,7 +4040,7 @@ function createBreadcrumb(
3889
4040
  breadcrumb,
3890
4041
  ) {
3891
4042
  return {
3892
- timestamp: new Date().getTime() / 1000,
4043
+ timestamp: Date.now() / 1000,
3893
4044
  type: 'default',
3894
4045
  ...breadcrumb,
3895
4046
  };
@@ -3926,6 +4077,40 @@ function addBreadcrumbEvent(replay, breadcrumb) {
3926
4077
  });
3927
4078
  }
3928
4079
 
4080
+ // Note that these are the serialized attributes and not attributes directly on
4081
+ // the DOM Node. Attributes we are interested in:
4082
+ const ATTRIBUTES_TO_RECORD = new Set([
4083
+ 'id',
4084
+ 'class',
4085
+ 'aria-label',
4086
+ 'role',
4087
+ 'name',
4088
+ 'alt',
4089
+ 'title',
4090
+ 'data-test-id',
4091
+ 'data-testid',
4092
+ ]);
4093
+
4094
+ /**
4095
+ * Inclusion list of attributes that we want to record from the DOM element
4096
+ */
4097
+ function getAttributesToRecord(attributes) {
4098
+ const obj = {};
4099
+ for (const key in attributes) {
4100
+ if (ATTRIBUTES_TO_RECORD.has(key)) {
4101
+ let normalizedKey = key;
4102
+
4103
+ if (key === 'data-testid' || key === 'data-test-id') {
4104
+ normalizedKey = 'testId';
4105
+ }
4106
+
4107
+ obj[normalizedKey] = attributes[key];
4108
+ }
4109
+ }
4110
+
4111
+ return obj;
4112
+ }
4113
+
3929
4114
  const handleDomListener =
3930
4115
  (replay) =>
3931
4116
  (handlerData) => {
@@ -3946,7 +4131,6 @@ const handleDomListener =
3946
4131
  * An event handler to react to DOM events.
3947
4132
  */
3948
4133
  function handleDom(handlerData) {
3949
- // Taken from https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/integrations/breadcrumbs.ts#L112
3950
4134
  let target;
3951
4135
  let targetNode;
3952
4136
 
@@ -3958,18 +4142,32 @@ function handleDom(handlerData) {
3958
4142
  target = '<unknown>';
3959
4143
  }
3960
4144
 
3961
- if (target.length === 0) {
3962
- return null;
3963
- }
4145
+ // `__sn` property is the serialized node created by rrweb
4146
+ const serializedNode =
4147
+ targetNode && '__sn' in targetNode && targetNode.__sn.type === NodeType.Element ? targetNode.__sn : null;
3964
4148
 
3965
4149
  return createBreadcrumb({
3966
4150
  category: `ui.${handlerData.name}`,
3967
4151
  message: target,
3968
- data: {
3969
- // Not sure why this errors, Node should be correct (Argument of type 'Node' is not assignable to parameter of type 'INode')
3970
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3971
- ...(targetNode ? { nodeId: record.mirror.getId(targetNode ) } : {}),
3972
- },
4152
+ data: serializedNode
4153
+ ? {
4154
+ nodeId: serializedNode.id,
4155
+ node: {
4156
+ id: serializedNode.id,
4157
+ tagName: serializedNode.tagName,
4158
+ textContent: targetNode
4159
+ ? Array.from(targetNode.childNodes)
4160
+ .map(
4161
+ (node) => '__sn' in node && node.__sn.type === NodeType.Text && node.__sn.textContent,
4162
+ )
4163
+ .filter(Boolean) // filter out empty values
4164
+ .map(text => (text ).trim())
4165
+ .join('')
4166
+ : '',
4167
+ attributes: getAttributesToRecord(serializedNode.attributes),
4168
+ },
4169
+ }
4170
+ : {},
3973
4171
  });
3974
4172
  }
3975
4173
 
@@ -3985,102 +4183,6 @@ function isEventWithTarget(event) {
3985
4183
  return !!(event ).target;
3986
4184
  }
3987
4185
 
3988
- /**
3989
- * Create a "span" for each performance entry. The parent transaction is `this.replayEvent`.
3990
- */
3991
- function createPerformanceSpans(
3992
- replay,
3993
- entries,
3994
- ) {
3995
- return entries.map(({ type, start, end, name, data }) =>
3996
- addEvent(replay, {
3997
- type: EventType.Custom,
3998
- timestamp: start,
3999
- data: {
4000
- tag: 'performanceSpan',
4001
- payload: {
4002
- op: type,
4003
- description: name,
4004
- startTimestamp: start,
4005
- endTimestamp: end,
4006
- data,
4007
- },
4008
- },
4009
- }),
4010
- );
4011
- }
4012
-
4013
- /**
4014
- * Check whether a given request URL should be filtered out. This is so we
4015
- * don't log Sentry ingest requests.
4016
- */
4017
- function shouldFilterRequest(replay, url) {
4018
- // If we enabled the `traceInternals` experiment, we want to trace everything
4019
- if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && replay.getOptions()._experiments.traceInternals) {
4020
- return false;
4021
- }
4022
-
4023
- return _isSentryRequest(url);
4024
- }
4025
-
4026
- /**
4027
- * Checks wether a given URL belongs to the configured Sentry DSN.
4028
- */
4029
- function _isSentryRequest(url) {
4030
- const client = core.getCurrentHub().getClient();
4031
- const dsn = client && client.getDsn();
4032
- return dsn ? url.includes(dsn.host) : false;
4033
- }
4034
-
4035
- /** only exported for tests */
4036
- function handleFetch(handlerData) {
4037
- if (!handlerData.endTimestamp) {
4038
- return null;
4039
- }
4040
-
4041
- const { startTimestamp, endTimestamp, fetchData, response } = handlerData;
4042
-
4043
- return {
4044
- type: 'resource.fetch',
4045
- start: startTimestamp / 1000,
4046
- end: endTimestamp / 1000,
4047
- name: fetchData.url,
4048
- data: {
4049
- method: fetchData.method,
4050
- statusCode: response.status,
4051
- },
4052
- };
4053
- }
4054
-
4055
- /**
4056
- * Returns a listener to be added to `addInstrumentationHandler('fetch', listener)`.
4057
- */
4058
- function handleFetchSpanListener(replay) {
4059
- return (handlerData) => {
4060
- if (!replay.isEnabled()) {
4061
- return;
4062
- }
4063
-
4064
- const result = handleFetch(handlerData);
4065
-
4066
- if (result === null) {
4067
- return;
4068
- }
4069
-
4070
- if (shouldFilterRequest(replay, result.name)) {
4071
- return;
4072
- }
4073
-
4074
- replay.addUpdate(() => {
4075
- createPerformanceSpans(replay, [result]);
4076
- // Returning true will cause `addUpdate` to not flush
4077
- // We do not want network requests to cause a flush. This will prevent
4078
- // recurring/polling requests from keeping the replay session alive.
4079
- return true;
4080
- });
4081
- };
4082
- }
4083
-
4084
4186
  /**
4085
4187
  * Returns true if we think the given event is an error originating inside of rrweb.
4086
4188
  */
@@ -4107,16 +4209,25 @@ function isRrwebError(event, hint) {
4107
4209
  /**
4108
4210
  * Returns a listener to be added to `addGlobalEventProcessor(listener)`.
4109
4211
  */
4110
- function handleGlobalEventListener(replay) {
4212
+ function handleGlobalEventListener(
4213
+ replay,
4214
+ includeAfterSendEventHandling = false,
4215
+ ) {
4216
+ const afterSendHandler = includeAfterSendEventHandling ? handleAfterSendEvent(replay) : undefined;
4217
+
4111
4218
  return (event, hint) => {
4112
- // Do not apply replayId to the root event
4113
- if (event.type === REPLAY_EVENT_NAME) {
4219
+ if (isReplayEvent(event)) {
4114
4220
  // Replays have separate set of breadcrumbs, do not include breadcrumbs
4115
4221
  // from core SDK
4116
4222
  delete event.breadcrumbs;
4117
4223
  return event;
4118
4224
  }
4119
4225
 
4226
+ // We only want to handle errors & transactions, nothing else
4227
+ if (!isErrorEvent(event) && !isTransactionEvent(event)) {
4228
+ return event;
4229
+ }
4230
+
4120
4231
  // Unless `captureExceptions` is enabled, we want to ignore errors coming from rrweb
4121
4232
  // As there can be a bunch of stuff going wrong in internals there, that we don't want to bubble up to users
4122
4233
  if (isRrwebError(event, hint) && !replay.getOptions()._experiments.captureExceptions) {
@@ -4125,50 +4236,22 @@ function handleGlobalEventListener(replay) {
4125
4236
  }
4126
4237
 
4127
4238
  // Only tag transactions with replayId if not waiting for an error
4128
- // @ts-ignore private
4129
- if (!event.type || replay.recordingMode === 'session') {
4239
+ if (isErrorEvent(event) || (isTransactionEvent(event) && replay.recordingMode === 'session')) {
4130
4240
  event.tags = { ...event.tags, replayId: replay.getSessionId() };
4131
4241
  }
4132
4242
 
4133
- // Collect traceIds in _context regardless of `recordingMode` - if it's true,
4134
- // _context gets cleared on every checkout
4135
- if (event.type === 'transaction' && event.contexts && event.contexts.trace && event.contexts.trace.trace_id) {
4136
- replay.getContext().traceIds.add(event.contexts.trace.trace_id );
4137
- return event;
4138
- }
4139
-
4140
- // no event type means error
4141
- if (!event.type) {
4142
- replay.getContext().errorIds.add(event.event_id );
4143
- }
4144
-
4145
- if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && replay.getOptions()._experiments.traceInternals) {
4243
+ if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && replay.getOptions()._experiments.traceInternals && isErrorEvent(event)) {
4146
4244
  const exc = getEventExceptionValues(event);
4147
4245
  addInternalBreadcrumb({
4148
4246
  message: `Tagging event (${event.event_id}) - ${event.message} - ${exc.type}: ${exc.value}`,
4149
4247
  });
4150
4248
  }
4151
4249
 
4152
- // Need to be very careful that this does not cause an infinite loop
4153
- if (
4154
- replay.recordingMode === 'error' &&
4155
- event.exception &&
4156
- event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because otherwise we could loop indefinitely with trying to capture replay and failing
4157
- ) {
4158
- setTimeout(async () => {
4159
- // Allow flush to complete before resuming as a session recording, otherwise
4160
- // the checkout from `startRecording` may be included in the payload.
4161
- // Prefer to keep the error replay as a separate (and smaller) segment
4162
- // than the session replay.
4163
- await replay.flushImmediate();
4164
-
4165
- if (replay.stopRecording()) {
4166
- // Reset all "capture on error" configuration before
4167
- // starting a new recording
4168
- replay.recordingMode = 'session';
4169
- replay.startRecording();
4170
- }
4171
- });
4250
+ // In cases where a custom client is used that does not support the new hooks (yet),
4251
+ // we manually call this hook method here
4252
+ if (afterSendHandler) {
4253
+ // Pretend the error had a 200 response so we always capture it
4254
+ afterSendHandler(event, { statusCode: 200 });
4172
4255
  }
4173
4256
 
4174
4257
  return event;
@@ -4194,29 +4277,54 @@ function getEventExceptionValues(event) {
4194
4277
  };
4195
4278
  }
4196
4279
 
4197
- function handleHistory(handlerData) {
4198
- const { from, to } = handlerData;
4199
-
4200
- const now = new Date().getTime() / 1000;
4201
-
4202
- return {
4203
- type: 'navigation.push',
4204
- start: now,
4205
- end: now,
4206
- name: to,
4207
- data: {
4208
- previous: from,
4209
- },
4210
- };
4211
- }
4212
-
4213
4280
  /**
4214
- * Returns a listener to be added to `addInstrumentationHandler('history', listener)`.
4281
+ * Create a "span" for each performance entry. The parent transaction is `this.replayEvent`.
4215
4282
  */
4216
- function handleHistorySpanListener(replay) {
4217
- return (handlerData) => {
4218
- if (!replay.isEnabled()) {
4219
- return;
4283
+ function createPerformanceSpans(
4284
+ replay,
4285
+ entries,
4286
+ ) {
4287
+ return entries.map(({ type, start, end, name, data }) =>
4288
+ addEvent(replay, {
4289
+ type: EventType.Custom,
4290
+ timestamp: start,
4291
+ data: {
4292
+ tag: 'performanceSpan',
4293
+ payload: {
4294
+ op: type,
4295
+ description: name,
4296
+ startTimestamp: start,
4297
+ endTimestamp: end,
4298
+ data,
4299
+ },
4300
+ },
4301
+ }),
4302
+ );
4303
+ }
4304
+
4305
+ function handleHistory(handlerData) {
4306
+ const { from, to } = handlerData;
4307
+
4308
+ const now = Date.now() / 1000;
4309
+
4310
+ return {
4311
+ type: 'navigation.push',
4312
+ start: now,
4313
+ end: now,
4314
+ name: to,
4315
+ data: {
4316
+ previous: from,
4317
+ },
4318
+ };
4319
+ }
4320
+
4321
+ /**
4322
+ * Returns a listener to be added to `addInstrumentationHandler('history', listener)`.
4323
+ */
4324
+ function handleHistorySpanListener(replay) {
4325
+ return (handlerData) => {
4326
+ if (!replay.isEnabled()) {
4327
+ return;
4220
4328
  }
4221
4329
 
4222
4330
  const result = handleHistory(handlerData);
@@ -4237,91 +4345,120 @@ function handleHistorySpanListener(replay) {
4237
4345
  };
4238
4346
  }
4239
4347
 
4240
- let _LAST_BREADCRUMB = null;
4241
-
4242
- const handleScopeListener =
4243
- (replay) =>
4244
- (scope) => {
4245
- if (!replay.isEnabled()) {
4246
- return;
4247
- }
4248
-
4249
- const result = handleScope(scope);
4250
-
4251
- if (!result) {
4252
- return;
4253
- }
4348
+ /**
4349
+ * Check whether a given request URL should be filtered out. This is so we
4350
+ * don't log Sentry ingest requests.
4351
+ */
4352
+ function shouldFilterRequest(replay, url) {
4353
+ // If we enabled the `traceInternals` experiment, we want to trace everything
4354
+ if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && replay.getOptions()._experiments.traceInternals) {
4355
+ return false;
4356
+ }
4254
4357
 
4255
- addBreadcrumbEvent(replay, result);
4256
- };
4358
+ return _isSentryRequest(url);
4359
+ }
4257
4360
 
4258
4361
  /**
4259
- * An event handler to handle scope changes.
4362
+ * Checks wether a given URL belongs to the configured Sentry DSN.
4260
4363
  */
4261
- function handleScope(scope) {
4262
- // TODO (v8): Remove this guard. This was put in place because we introduced
4263
- // Scope.getLastBreadcrumb mid-v7 which caused incompatibilities with older SDKs.
4264
- // For now, we'll just return null if the method doesn't exist but we should eventually
4265
- // get rid of this guard.
4266
- const newBreadcrumb = scope.getLastBreadcrumb && scope.getLastBreadcrumb();
4364
+ function _isSentryRequest(url) {
4365
+ const client = core.getCurrentHub().getClient();
4366
+ const dsn = client && client.getDsn();
4367
+ return dsn ? url.includes(dsn.host) : false;
4368
+ }
4267
4369
 
4268
- // Listener can be called when breadcrumbs have not changed, so we store the
4269
- // reference to the last crumb and only return a crumb if it has changed
4270
- if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {
4271
- return null;
4370
+ /** Add a performance entry breadcrumb */
4371
+ function addNetworkBreadcrumb(replay, result) {
4372
+ if (!replay.isEnabled()) {
4373
+ return;
4272
4374
  }
4273
4375
 
4274
- _LAST_BREADCRUMB = newBreadcrumb;
4376
+ if (result === null) {
4377
+ return;
4378
+ }
4275
4379
 
4276
- if (
4277
- newBreadcrumb.category &&
4278
- (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||
4279
- newBreadcrumb.category.startsWith('ui.'))
4280
- ) {
4281
- return null;
4380
+ if (shouldFilterRequest(replay, result.name)) {
4381
+ return;
4282
4382
  }
4283
4383
 
4284
- return createBreadcrumb(newBreadcrumb);
4384
+ replay.addUpdate(() => {
4385
+ createPerformanceSpans(replay, [result]);
4386
+ // Returning true will cause `addUpdate` to not flush
4387
+ // We do not want network requests to cause a flush. This will prevent
4388
+ // recurring/polling requests from keeping the replay session alive.
4389
+ return true;
4390
+ });
4285
4391
  }
4286
4392
 
4287
- // From sentry-javascript
4288
- // e.g. https://github.com/getsentry/sentry-javascript/blob/c7fc025bf9fa8c073fdb56351808ce53909fbe45/packages/utils/src/instrument.ts#L180
4393
+ /** only exported for tests */
4394
+ function handleFetch(handlerData) {
4395
+ const { startTimestamp, endTimestamp, fetchData, response } = handlerData;
4289
4396
 
4290
- function handleXhr(handlerData) {
4291
- if (handlerData.xhr.__sentry_own_request__) {
4292
- // Taken from sentry-javascript
4293
- // Only capture non-sentry requests
4397
+ if (!endTimestamp) {
4294
4398
  return null;
4295
4399
  }
4296
4400
 
4297
- if (handlerData.startTimestamp) {
4298
- // TODO: See if this is still needed
4299
- handlerData.xhr.__sentry_xhr__ = handlerData.xhr.__sentry_xhr__ || {};
4300
- handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
4301
- }
4401
+ const { method, request_body_size: requestBodySize, response_body_size: responseBodySize } = fetchData;
4402
+
4403
+ return {
4404
+ type: 'resource.fetch',
4405
+ start: startTimestamp / 1000,
4406
+ end: endTimestamp / 1000,
4407
+ name: fetchData.url,
4408
+ data: {
4409
+ method,
4410
+ statusCode: response && (response ).status,
4411
+ requestBodySize,
4412
+ responseBodySize,
4413
+ },
4414
+ };
4415
+ }
4416
+
4417
+ /**
4418
+ * Returns a listener to be added to `addInstrumentationHandler('fetch', listener)`.
4419
+ */
4420
+ function handleFetchSpanListener(replay) {
4421
+ return (handlerData) => {
4422
+ if (!replay.isEnabled()) {
4423
+ return;
4424
+ }
4425
+
4426
+ const result = handleFetch(handlerData);
4302
4427
 
4303
- if (!handlerData.endTimestamp) {
4428
+ addNetworkBreadcrumb(replay, result);
4429
+ };
4430
+ }
4431
+
4432
+ /** only exported for tests */
4433
+ function handleXhr(handlerData) {
4434
+ const { startTimestamp, endTimestamp, xhr } = handlerData;
4435
+
4436
+ if (!startTimestamp || !endTimestamp || !xhr.__sentry_xhr__) {
4304
4437
  return null;
4305
4438
  }
4306
4439
 
4307
- const { method, url, status_code: statusCode } = handlerData.xhr.__sentry_xhr__ || {};
4440
+ const {
4441
+ method,
4442
+ url,
4443
+ status_code: statusCode,
4444
+ request_body_size: requestBodySize,
4445
+ response_body_size: responseBodySize,
4446
+ } = xhr.__sentry_xhr__;
4308
4447
 
4309
4448
  if (url === undefined) {
4310
4449
  return null;
4311
4450
  }
4312
4451
 
4313
- const timestamp = handlerData.xhr.__sentry_xhr__
4314
- ? handlerData.xhr.__sentry_xhr__.startTimestamp || 0
4315
- : handlerData.endTimestamp;
4316
-
4317
4452
  return {
4318
4453
  type: 'resource.xhr',
4319
4454
  name: url,
4320
- start: timestamp / 1000,
4321
- end: handlerData.endTimestamp / 1000,
4455
+ start: startTimestamp / 1000,
4456
+ end: endTimestamp / 1000,
4322
4457
  data: {
4323
4458
  method,
4324
4459
  statusCode,
4460
+ requestBodySize,
4461
+ responseBodySize,
4325
4462
  },
4326
4463
  };
4327
4464
  }
@@ -4337,22 +4474,280 @@ function handleXhrSpanListener(replay) {
4337
4474
 
4338
4475
  const result = handleXhr(handlerData);
4339
4476
 
4340
- if (result === null) {
4477
+ addNetworkBreadcrumb(replay, result);
4478
+ };
4479
+ }
4480
+
4481
+ /**
4482
+ * This will enrich the xhr/fetch breadcrumbs with additional information.
4483
+ *
4484
+ * This adds:
4485
+ * * request_body_size
4486
+ * * response_body_size
4487
+ *
4488
+ * to the breadcrumb data.
4489
+ */
4490
+ function handleNetworkBreadcrumbs(replay) {
4491
+ const client = core.getCurrentHub().getClient();
4492
+
4493
+ try {
4494
+ const textEncoder = new TextEncoder();
4495
+
4496
+ const options = {
4497
+ replay,
4498
+ textEncoder,
4499
+ };
4500
+
4501
+ if (client && client.on) {
4502
+ client.on('beforeAddBreadcrumb', (breadcrumb, hint) => handleNetworkBreadcrumb(options, breadcrumb, hint));
4503
+ } else {
4504
+ // Fallback behavior
4505
+ utils.addInstrumentationHandler('fetch', handleFetchSpanListener(replay));
4506
+ utils.addInstrumentationHandler('xhr', handleXhrSpanListener(replay));
4507
+ }
4508
+ } catch (e2) {
4509
+ // Do nothing
4510
+ }
4511
+ }
4512
+
4513
+ /** just exported for tests */
4514
+ function handleNetworkBreadcrumb(
4515
+ options,
4516
+ breadcrumb,
4517
+ hint,
4518
+ ) {
4519
+ if (!breadcrumb.data) {
4520
+ return;
4521
+ }
4522
+
4523
+ try {
4524
+ if (_isXhrBreadcrumb(breadcrumb) && _isXhrHint(hint)) {
4525
+ // Enriches the breadcrumb overall
4526
+ _enrichXhrBreadcrumb(breadcrumb, hint, options);
4527
+
4528
+ // Create a replay performance entry from this breadcrumb
4529
+ const result = _makeNetworkReplayBreadcrumb('resource.xhr', breadcrumb, hint);
4530
+ addNetworkBreadcrumb(options.replay, result);
4531
+ }
4532
+
4533
+ if (_isFetchBreadcrumb(breadcrumb) && _isFetchHint(hint)) {
4534
+ // Enriches the breadcrumb overall
4535
+ _enrichFetchBreadcrumb(breadcrumb, hint, options);
4536
+
4537
+ // Create a replay performance entry from this breadcrumb
4538
+ const result = _makeNetworkReplayBreadcrumb('resource.fetch', breadcrumb, hint);
4539
+ addNetworkBreadcrumb(options.replay, result);
4540
+ }
4541
+ } catch (e) {
4542
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.warn('Error when enriching network breadcrumb');
4543
+ }
4544
+ }
4545
+
4546
+ function _makeNetworkReplayBreadcrumb(
4547
+ type,
4548
+ breadcrumb,
4549
+ hint,
4550
+ ) {
4551
+ const { startTimestamp, endTimestamp } = hint;
4552
+
4553
+ if (!endTimestamp) {
4554
+ return null;
4555
+ }
4556
+
4557
+ const {
4558
+ url,
4559
+ method,
4560
+ status_code: statusCode,
4561
+ request_body_size: requestBodySize,
4562
+ response_body_size: responseBodySize,
4563
+ } = breadcrumb.data;
4564
+
4565
+ if (url === undefined) {
4566
+ return null;
4567
+ }
4568
+
4569
+ const result = {
4570
+ type,
4571
+ start: startTimestamp / 1000,
4572
+ end: endTimestamp / 1000,
4573
+ name: url,
4574
+ data: {
4575
+ method,
4576
+ statusCode,
4577
+ },
4578
+ };
4579
+
4580
+ if (requestBodySize) {
4581
+ result.data.requestBodySize = requestBodySize;
4582
+ }
4583
+ if (responseBodySize) {
4584
+ result.data.responseBodySize = responseBodySize;
4585
+ }
4586
+
4587
+ return result;
4588
+ }
4589
+
4590
+ function _enrichXhrBreadcrumb(
4591
+ breadcrumb,
4592
+ hint,
4593
+ options,
4594
+ ) {
4595
+ const { xhr, input } = hint;
4596
+
4597
+ const reqSize = getBodySize(input, options.textEncoder);
4598
+ const resSize = xhr.getResponseHeader('content-length')
4599
+ ? parseContentSizeHeader(xhr.getResponseHeader('content-length'))
4600
+ : getBodySize(xhr.response, options.textEncoder);
4601
+
4602
+ if (reqSize !== undefined) {
4603
+ breadcrumb.data.request_body_size = reqSize;
4604
+ }
4605
+ if (resSize !== undefined) {
4606
+ breadcrumb.data.response_body_size = resSize;
4607
+ }
4608
+ }
4609
+
4610
+ function _enrichFetchBreadcrumb(
4611
+ breadcrumb,
4612
+ hint,
4613
+ options,
4614
+ ) {
4615
+ const { input, response } = hint;
4616
+
4617
+ const body = getFetchBody(input);
4618
+ const reqSize = getBodySize(body, options.textEncoder);
4619
+ const resSize = response ? parseContentSizeHeader(response.headers.get('content-length')) : undefined;
4620
+
4621
+ if (reqSize !== undefined) {
4622
+ breadcrumb.data.request_body_size = reqSize;
4623
+ }
4624
+ if (resSize !== undefined) {
4625
+ breadcrumb.data.response_body_size = resSize;
4626
+ }
4627
+ }
4628
+
4629
+ /** only exported for tests */
4630
+ function getBodySize(
4631
+ body,
4632
+ textEncoder,
4633
+ ) {
4634
+ if (!body) {
4635
+ return undefined;
4636
+ }
4637
+
4638
+ try {
4639
+ if (typeof body === 'string') {
4640
+ return textEncoder.encode(body).length;
4641
+ }
4642
+
4643
+ if (body instanceof URLSearchParams) {
4644
+ return textEncoder.encode(body.toString()).length;
4645
+ }
4646
+
4647
+ if (body instanceof FormData) {
4648
+ // This is a bit simplified, but gives us a decent estimate
4649
+ // This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'
4650
+ // @ts-ignore passing FormData to URLSearchParams actually works
4651
+ const formDataStr = new URLSearchParams(body).toString();
4652
+ return textEncoder.encode(formDataStr).length;
4653
+ }
4654
+
4655
+ if (body instanceof Blob) {
4656
+ return body.size;
4657
+ }
4658
+
4659
+ if (body instanceof ArrayBuffer) {
4660
+ return body.byteLength;
4661
+ }
4662
+
4663
+ // Currently unhandled types: ArrayBufferView, ReadableStream
4664
+ } catch (e3) {
4665
+ // just return undefined
4666
+ }
4667
+
4668
+ return undefined;
4669
+ }
4670
+
4671
+ /** only exported for tests */
4672
+ function parseContentSizeHeader(header) {
4673
+ if (!header) {
4674
+ return undefined;
4675
+ }
4676
+
4677
+ const size = parseInt(header, 10);
4678
+ return isNaN(size) ? undefined : size;
4679
+ }
4680
+
4681
+ function getFetchBody(fetchArgs = []) {
4682
+ // We only support getting the body from the fetch options
4683
+ if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== 'object') {
4684
+ return undefined;
4685
+ }
4686
+
4687
+ return (fetchArgs[1] ).body;
4688
+ }
4689
+
4690
+ function _isXhrBreadcrumb(breadcrumb) {
4691
+ return breadcrumb.category === 'xhr';
4692
+ }
4693
+
4694
+ function _isFetchBreadcrumb(breadcrumb) {
4695
+ return breadcrumb.category === 'fetch';
4696
+ }
4697
+
4698
+ function _isXhrHint(hint) {
4699
+ return hint && hint.xhr;
4700
+ }
4701
+
4702
+ function _isFetchHint(hint) {
4703
+ return hint && hint.response;
4704
+ }
4705
+
4706
+ let _LAST_BREADCRUMB = null;
4707
+
4708
+ const handleScopeListener =
4709
+ (replay) =>
4710
+ (scope) => {
4711
+ if (!replay.isEnabled()) {
4341
4712
  return;
4342
4713
  }
4343
4714
 
4344
- if (shouldFilterRequest(replay, result.name)) {
4715
+ const result = handleScope(scope);
4716
+
4717
+ if (!result) {
4345
4718
  return;
4346
4719
  }
4347
4720
 
4348
- replay.addUpdate(() => {
4349
- createPerformanceSpans(replay, [result]);
4350
- // Returning true will cause `addUpdate` to not flush
4351
- // We do not want network requests to cause a flush. This will prevent
4352
- // recurring/polling requests from keeping the replay session alive.
4353
- return true;
4354
- });
4721
+ addBreadcrumbEvent(replay, result);
4355
4722
  };
4723
+
4724
+ /**
4725
+ * An event handler to handle scope changes.
4726
+ */
4727
+ function handleScope(scope) {
4728
+ // TODO (v8): Remove this guard. This was put in place because we introduced
4729
+ // Scope.getLastBreadcrumb mid-v7 which caused incompatibilities with older SDKs.
4730
+ // For now, we'll just return null if the method doesn't exist but we should eventually
4731
+ // get rid of this guard.
4732
+ const newBreadcrumb = scope.getLastBreadcrumb && scope.getLastBreadcrumb();
4733
+
4734
+ // Listener can be called when breadcrumbs have not changed, so we store the
4735
+ // reference to the last crumb and only return a crumb if it has changed
4736
+ if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {
4737
+ return null;
4738
+ }
4739
+
4740
+ _LAST_BREADCRUMB = newBreadcrumb;
4741
+
4742
+ if (
4743
+ newBreadcrumb.category &&
4744
+ (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||
4745
+ newBreadcrumb.category.startsWith('ui.'))
4746
+ ) {
4747
+ return null;
4748
+ }
4749
+
4750
+ return createBreadcrumb(newBreadcrumb);
4356
4751
  }
4357
4752
 
4358
4753
  /**
@@ -4361,17 +4756,26 @@ function handleXhrSpanListener(replay) {
4361
4756
  function addGlobalListeners(replay) {
4362
4757
  // Listeners from core SDK //
4363
4758
  const scope = core.getCurrentHub().getScope();
4759
+ const client = core.getCurrentHub().getClient();
4760
+
4364
4761
  if (scope) {
4365
4762
  scope.addScopeListener(handleScopeListener(replay));
4366
4763
  }
4367
4764
  utils.addInstrumentationHandler('dom', handleDomListener(replay));
4368
- utils.addInstrumentationHandler('fetch', handleFetchSpanListener(replay));
4369
- utils.addInstrumentationHandler('xhr', handleXhrSpanListener(replay));
4370
4765
  utils.addInstrumentationHandler('history', handleHistorySpanListener(replay));
4766
+ handleNetworkBreadcrumbs(replay);
4767
+
4768
+ // If a custom client has no hooks yet, we continue to use the "old" implementation
4769
+ const hasHooks = !!(client && client.on);
4371
4770
 
4372
4771
  // Tag all (non replay) events that get sent to Sentry with the current
4373
4772
  // replay ID so that we can reference them later in the UI
4374
- core.addGlobalEventProcessor(handleGlobalEventListener(replay));
4773
+ core.addGlobalEventProcessor(handleGlobalEventListener(replay, !hasHooks));
4774
+
4775
+ if (hasHooks) {
4776
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4777
+ (client ).on('afterSendEvent', handleAfterSendEvent(replay));
4778
+ }
4375
4779
  }
4376
4780
 
4377
4781
  /**
@@ -4397,7 +4801,7 @@ function createMemoryEntry(memoryEntry) {
4397
4801
  const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = memoryEntry;
4398
4802
  // we don't want to use `getAbsoluteTime` because it adds the event time to the
4399
4803
  // time origin, so we get the current timestamp instead
4400
- const time = new Date().getTime() / 1000;
4804
+ const time = Date.now() / 1000;
4401
4805
  return {
4402
4806
  type: 'memory',
4403
4807
  name: 'memory',
@@ -4684,49 +5088,6 @@ function getHandleRecordingEmit(replay) {
4684
5088
  };
4685
5089
  }
4686
5090
 
4687
- let _originalRecordDroppedEvent;
4688
-
4689
- /**
4690
- * Overwrite the `recordDroppedEvent` method on the client, so we can find out which events were dropped.
4691
- * */
4692
- function overwriteRecordDroppedEvent(errorIds) {
4693
- const client = core.getCurrentHub().getClient();
4694
-
4695
- if (!client) {
4696
- return;
4697
- }
4698
-
4699
- const _originalCallback = client.recordDroppedEvent.bind(client);
4700
-
4701
- const recordDroppedEvent = (
4702
- reason,
4703
- category,
4704
- event,
4705
- ) => {
4706
- if (event && !event.type && event.event_id) {
4707
- errorIds.delete(event.event_id);
4708
- }
4709
-
4710
- return _originalCallback(reason, category, event);
4711
- };
4712
-
4713
- client.recordDroppedEvent = recordDroppedEvent;
4714
- _originalRecordDroppedEvent = _originalCallback;
4715
- }
4716
-
4717
- /**
4718
- * Restore the original method.
4719
- * */
4720
- function restoreRecordDroppedEvent() {
4721
- const client = core.getCurrentHub().getClient();
4722
-
4723
- if (!client || !_originalRecordDroppedEvent) {
4724
- return;
4725
- }
4726
-
4727
- client.recordDroppedEvent = _originalRecordDroppedEvent;
4728
- }
4729
-
4730
5091
  /**
4731
5092
  * Create a replay envelope ready to be sent.
4732
5093
  * This includes both the replay event, as well as the recording data.
@@ -5079,7 +5440,7 @@ class ReplayContainer {
5079
5440
  /**
5080
5441
  * Timestamp of the last user activity. This lives across sessions.
5081
5442
  */
5082
- __init7() {this._lastActivity = new Date().getTime();}
5443
+ __init7() {this._lastActivity = Date.now();}
5083
5444
 
5084
5445
  /**
5085
5446
  * Is the integration currently active?
@@ -5109,7 +5470,7 @@ class ReplayContainer {
5109
5470
  traceIds: new Set(),
5110
5471
  urls: [],
5111
5472
  earliestEvent: null,
5112
- initialTimestamp: new Date().getTime(),
5473
+ initialTimestamp: Date.now(),
5113
5474
  initialUrl: '',
5114
5475
  };}
5115
5476
 
@@ -5391,11 +5752,19 @@ class ReplayContainer {
5391
5752
  const oldSessionId = this.getSessionId();
5392
5753
 
5393
5754
  // Prevent starting a new session if the last user activity is older than
5394
- // MAX_SESSION_LIFE. Otherwise non-user activity can trigger a new
5755
+ // SESSION_IDLE_DURATION. Otherwise non-user activity can trigger a new
5395
5756
  // session+recording. This creates noisy replays that do not have much
5396
5757
  // content in them.
5397
- if (this._lastActivity && isExpired(this._lastActivity, this.timeouts.maxSessionLife)) {
5398
- // Pause recording
5758
+ if (
5759
+ this._lastActivity &&
5760
+ isExpired(this._lastActivity, this.timeouts.sessionIdle) &&
5761
+ this.session &&
5762
+ this.session.sampled === 'session'
5763
+ ) {
5764
+ // Pause recording only for session-based replays. Otherwise, resuming
5765
+ // will create a new replay and will conflict with users who only choose
5766
+ // to record error-based replays only. (e.g. the resumed replay will not
5767
+ // contain a reference to an error)
5399
5768
  this.pause();
5400
5769
  return;
5401
5770
  }
@@ -5434,7 +5803,7 @@ class ReplayContainer {
5434
5803
  this._clearContext();
5435
5804
 
5436
5805
  this._context.initialUrl = url;
5437
- this._context.initialTimestamp = new Date().getTime();
5806
+ this._context.initialTimestamp = Date.now();
5438
5807
  this._context.urls.push(url);
5439
5808
  }
5440
5809
 
@@ -5490,9 +5859,6 @@ class ReplayContainer {
5490
5859
  WINDOW.addEventListener('blur', this._handleWindowBlur);
5491
5860
  WINDOW.addEventListener('focus', this._handleWindowFocus);
5492
5861
 
5493
- // We need to filter out dropped events captured by `addGlobalEventProcessor(this.handleGlobalEvent)` below
5494
- overwriteRecordDroppedEvent(this._context.errorIds);
5495
-
5496
5862
  // There is no way to remove these listeners, so ensure they are only added once
5497
5863
  if (!this._hasInitializedCoreListeners) {
5498
5864
  addGlobalListeners(this);
@@ -5521,8 +5887,6 @@ class ReplayContainer {
5521
5887
  WINDOW.removeEventListener('blur', this._handleWindowBlur);
5522
5888
  WINDOW.removeEventListener('focus', this._handleWindowFocus);
5523
5889
 
5524
- restoreRecordDroppedEvent();
5525
-
5526
5890
  if (this._performanceObserver) {
5527
5891
  this._performanceObserver.disconnect();
5528
5892
  this._performanceObserver = null;
@@ -5631,14 +5995,14 @@ class ReplayContainer {
5631
5995
  /**
5632
5996
  * Update user activity (across session lifespans)
5633
5997
  */
5634
- _updateUserActivity(_lastActivity = new Date().getTime()) {
5998
+ _updateUserActivity(_lastActivity = Date.now()) {
5635
5999
  this._lastActivity = _lastActivity;
5636
6000
  }
5637
6001
 
5638
6002
  /**
5639
6003
  * Updates the session's last activity timestamp
5640
6004
  */
5641
- _updateSessionActivity(_lastActivity = new Date().getTime()) {
6005
+ _updateSessionActivity(_lastActivity = Date.now()) {
5642
6006
  if (this.session) {
5643
6007
  this.session.lastActivity = _lastActivity;
5644
6008
  this._maybeSaveSession();
@@ -5765,7 +6129,7 @@ class ReplayContainer {
5765
6129
  eventContext,
5766
6130
  session: this.session,
5767
6131
  options: this.getOptions(),
5768
- timestamp: new Date().getTime(),
6132
+ timestamp: Date.now(),
5769
6133
  });
5770
6134
  } catch (err) {
5771
6135
  this._handleException(err);
@@ -5911,7 +6275,7 @@ function getPrivacyOptions({
5911
6275
  blockSelector,
5912
6276
  ),
5913
6277
  unblockSelector: getOption(unblock, ['.sentry-unblock', '[data-sentry-unblock]']),
5914
- ignoreSelector: getOption(ignore, ['.sentry-ignore', '[data-sentry-ignore]'], ignoreClass),
6278
+ ignoreSelector: getOption(ignore, ['.sentry-ignore', '[data-sentry-ignore]', 'input[type="file"]'], ignoreClass),
5915
6279
  };
5916
6280
 
5917
6281
  if (blockClass instanceof RegExp) {