@sentry/replay 7.47.0 → 7.49.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 (33) hide show
  1. package/README.md +5 -0
  2. package/cjs/index.js +607 -60
  3. package/cjs/index.js.map +1 -1
  4. package/esm/index.js +608 -61
  5. package/esm/index.js.map +1 -1
  6. package/package.json +5 -5
  7. package/types/constants.d.ts +1 -1
  8. package/types/coreHandlers/handleNetworkBreadcrumbs.d.ts +2 -3
  9. package/types/coreHandlers/handleNetworkBreadcrumbs.d.ts.map +1 -1
  10. package/types/coreHandlers/handleXhr.d.ts.map +1 -1
  11. package/types/coreHandlers/util/addBreadcrumbEvent.d.ts.map +1 -1
  12. package/types/coreHandlers/util/fetchUtils.d.ts +2 -3
  13. package/types/coreHandlers/util/fetchUtils.d.ts.map +1 -1
  14. package/types/coreHandlers/util/networkUtils.d.ts +3 -1
  15. package/types/coreHandlers/util/networkUtils.d.ts.map +1 -1
  16. package/types/coreHandlers/util/xhrUtils.d.ts +2 -3
  17. package/types/coreHandlers/util/xhrUtils.d.ts.map +1 -1
  18. package/types/integration.d.ts +4 -0
  19. package/types/integration.d.ts.map +1 -1
  20. package/types/replay.d.ts +8 -1
  21. package/types/replay.d.ts.map +1 -1
  22. package/types/types.d.ts +26 -4
  23. package/types/types.d.ts.map +1 -1
  24. package/types/util/sendReplayRequest.d.ts +1 -1
  25. package/types/util/sendReplayRequest.d.ts.map +1 -1
  26. package/types/util/truncateJson/completeJson.d.ts +9 -0
  27. package/types/util/truncateJson/completeJson.d.ts.map +1 -0
  28. package/types/util/truncateJson/constants.d.ts +12 -0
  29. package/types/util/truncateJson/constants.d.ts.map +1 -0
  30. package/types/util/truncateJson/evaluateJson.d.ts +6 -0
  31. package/types/util/truncateJson/evaluateJson.d.ts.map +1 -0
  32. package/types/util/truncateJson/fixJson.d.ts +6 -0
  33. package/types/util/truncateJson/fixJson.d.ts.map +1 -0
package/cjs/index.js CHANGED
@@ -31,8 +31,8 @@ const ERROR_CHECKOUT_TIME = 60000;
31
31
  const RETRY_BASE_INTERVAL = 5000;
32
32
  const RETRY_MAX_COUNT = 3;
33
33
 
34
- /* The max (uncompressed) size in bytes of a network body. Any body larger than this will be dropped. */
35
- const NETWORK_BODY_MAX_SIZE = 300000;
34
+ /* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */
35
+ const NETWORK_BODY_MAX_SIZE = 150000;
36
36
 
37
37
  var NodeType$1;
38
38
  (function (NodeType) {
@@ -4071,7 +4071,8 @@ function addBreadcrumbEvent(replay, breadcrumb) {
4071
4071
  timestamp: (breadcrumb.timestamp || 0) * 1000,
4072
4072
  data: {
4073
4073
  tag: 'breadcrumb',
4074
- payload: utils.normalize(breadcrumb),
4074
+ // normalize to max. 10 depth and 1_000 properties per object
4075
+ payload: utils.normalize(breadcrumb, 10, 1000),
4075
4076
  },
4076
4077
  });
4077
4078
 
@@ -4438,12 +4439,14 @@ function handleFetchSpanListener(replay) {
4438
4439
  function handleXhr(handlerData) {
4439
4440
  const { startTimestamp, endTimestamp, xhr } = handlerData;
4440
4441
 
4441
- if (!startTimestamp || !endTimestamp || !xhr.__sentry_xhr__) {
4442
+ const sentryXhrData = xhr[utils.SENTRY_XHR_DATA_KEY];
4443
+
4444
+ if (!startTimestamp || !endTimestamp || !sentryXhrData) {
4442
4445
  return null;
4443
4446
  }
4444
4447
 
4445
4448
  // This is only used as a fallback, so we know the body sizes are never set here
4446
- const { method, url, status_code: statusCode } = xhr.__sentry_xhr__;
4449
+ const { method, url, status_code: statusCode } = sentryXhrData;
4447
4450
 
4448
4451
  if (url === undefined) {
4449
4452
  return null;
@@ -4476,6 +4479,393 @@ function handleXhrSpanListener(replay) {
4476
4479
  };
4477
4480
  }
4478
4481
 
4482
+ const OBJ = 10;
4483
+ const OBJ_KEY = 11;
4484
+ const OBJ_KEY_STR = 12;
4485
+ const OBJ_VAL = 13;
4486
+ const OBJ_VAL_STR = 14;
4487
+ const OBJ_VAL_COMPLETED = 15;
4488
+
4489
+ const ARR = 20;
4490
+ const ARR_VAL = 21;
4491
+ const ARR_VAL_STR = 22;
4492
+ const ARR_VAL_COMPLETED = 23;
4493
+
4494
+ const ALLOWED_PRIMITIVES = ['true', 'false', 'null'];
4495
+
4496
+ /**
4497
+ * Complete an incomplete JSON string.
4498
+ * This will ensure that the last element always has a `"~~"` to indicate it was truncated.
4499
+ * For example, `[1,2,` will be completed to `[1,2,"~~"]`
4500
+ * and `{"aa":"b` will be completed to `{"aa":"b~~"}`
4501
+ */
4502
+ function completeJson(incompleteJson, stack) {
4503
+ if (!stack.length) {
4504
+ return incompleteJson;
4505
+ }
4506
+
4507
+ let json = incompleteJson;
4508
+
4509
+ // Most checks are only needed for the last step in the stack
4510
+ const lastPos = stack.length - 1;
4511
+ const lastStep = stack[lastPos];
4512
+
4513
+ json = _fixLastStep(json, lastStep);
4514
+
4515
+ // Complete remaining steps - just add closing brackets
4516
+ for (let i = lastPos; i >= 0; i--) {
4517
+ const step = stack[i];
4518
+
4519
+ switch (step) {
4520
+ case OBJ:
4521
+ json = `${json}}`;
4522
+ break;
4523
+ case ARR:
4524
+ json = `${json}]`;
4525
+ break;
4526
+ }
4527
+ }
4528
+
4529
+ return json;
4530
+ }
4531
+
4532
+ function _fixLastStep(json, lastStep) {
4533
+ switch (lastStep) {
4534
+ // Object cases
4535
+ case OBJ:
4536
+ return `${json}"~~":"~~"`;
4537
+ case OBJ_KEY:
4538
+ return `${json}:"~~"`;
4539
+ case OBJ_KEY_STR:
4540
+ return `${json}~~":"~~"`;
4541
+ case OBJ_VAL:
4542
+ return _maybeFixIncompleteObjValue(json);
4543
+ case OBJ_VAL_STR:
4544
+ return `${json}~~"`;
4545
+ case OBJ_VAL_COMPLETED:
4546
+ return `${json},"~~":"~~"`;
4547
+
4548
+ // Array cases
4549
+ case ARR:
4550
+ return `${json}"~~"`;
4551
+ case ARR_VAL:
4552
+ return _maybeFixIncompleteArrValue(json);
4553
+ case ARR_VAL_STR:
4554
+ return `${json}~~"`;
4555
+ case ARR_VAL_COMPLETED:
4556
+ return `${json},"~~"`;
4557
+ }
4558
+
4559
+ return json;
4560
+ }
4561
+
4562
+ function _maybeFixIncompleteArrValue(json) {
4563
+ const pos = _findLastArrayDelimiter(json);
4564
+
4565
+ if (pos > -1) {
4566
+ const part = json.slice(pos + 1);
4567
+
4568
+ if (ALLOWED_PRIMITIVES.includes(part.trim())) {
4569
+ return `${json},"~~"`;
4570
+ }
4571
+
4572
+ // Everything else is replaced with `"~~"`
4573
+ return `${json.slice(0, pos + 1)}"~~"`;
4574
+ }
4575
+
4576
+ // fallback, this shouldn't happen, to be save
4577
+ return json;
4578
+ }
4579
+
4580
+ function _findLastArrayDelimiter(json) {
4581
+ for (let i = json.length - 1; i >= 0; i--) {
4582
+ const char = json[i];
4583
+
4584
+ if (char === ',' || char === '[') {
4585
+ return i;
4586
+ }
4587
+ }
4588
+
4589
+ return -1;
4590
+ }
4591
+
4592
+ function _maybeFixIncompleteObjValue(json) {
4593
+ const startPos = json.lastIndexOf(':');
4594
+
4595
+ const part = json.slice(startPos + 1);
4596
+
4597
+ if (ALLOWED_PRIMITIVES.includes(part.trim())) {
4598
+ return `${json},"~~":"~~"`;
4599
+ }
4600
+
4601
+ // Everything else is replaced with `"~~"`
4602
+ // This also means we do not have incomplete numbers, e.g `[1` is replaced with `["~~"]`
4603
+ return `${json.slice(0, startPos + 1)}"~~"`;
4604
+ }
4605
+
4606
+ /**
4607
+ * Evaluate an (incomplete) JSON string.
4608
+ */
4609
+ function evaluateJson(json) {
4610
+ const stack = [];
4611
+
4612
+ for (let pos = 0; pos < json.length; pos++) {
4613
+ _evaluateJsonPos(stack, json, pos);
4614
+ }
4615
+
4616
+ return stack;
4617
+ }
4618
+
4619
+ function _evaluateJsonPos(stack, json, pos) {
4620
+ const curStep = stack[stack.length - 1];
4621
+
4622
+ const char = json[pos];
4623
+
4624
+ const whitespaceRegex = /\s/;
4625
+
4626
+ if (whitespaceRegex.test(char)) {
4627
+ return;
4628
+ }
4629
+
4630
+ if (char === '"' && !_isEscaped(json, pos)) {
4631
+ _handleQuote(stack, curStep);
4632
+ return;
4633
+ }
4634
+
4635
+ switch (char) {
4636
+ case '{':
4637
+ _handleObj(stack, curStep);
4638
+ break;
4639
+ case '[':
4640
+ _handleArr(stack, curStep);
4641
+ break;
4642
+ case ':':
4643
+ _handleColon(stack, curStep);
4644
+ break;
4645
+ case ',':
4646
+ _handleComma(stack, curStep);
4647
+ break;
4648
+ case '}':
4649
+ _handleObjClose(stack, curStep);
4650
+ break;
4651
+ case ']':
4652
+ _handleArrClose(stack, curStep);
4653
+ break;
4654
+ }
4655
+ }
4656
+
4657
+ function _handleQuote(stack, curStep) {
4658
+ // End of obj value
4659
+ if (curStep === OBJ_VAL_STR) {
4660
+ stack.pop();
4661
+ stack.push(OBJ_VAL_COMPLETED);
4662
+ return;
4663
+ }
4664
+
4665
+ // End of arr value
4666
+ if (curStep === ARR_VAL_STR) {
4667
+ stack.pop();
4668
+ stack.push(ARR_VAL_COMPLETED);
4669
+ return;
4670
+ }
4671
+
4672
+ // Start of obj value
4673
+ if (curStep === OBJ_VAL) {
4674
+ stack.push(OBJ_VAL_STR);
4675
+ return;
4676
+ }
4677
+
4678
+ // Start of arr value
4679
+ if (curStep === ARR_VAL) {
4680
+ stack.push(ARR_VAL_STR);
4681
+ return;
4682
+ }
4683
+
4684
+ // Start of obj key
4685
+ if (curStep === OBJ) {
4686
+ stack.push(OBJ_KEY_STR);
4687
+ return;
4688
+ }
4689
+
4690
+ // End of obj key
4691
+ if (curStep === OBJ_KEY_STR) {
4692
+ stack.pop();
4693
+ stack.push(OBJ_KEY);
4694
+ return;
4695
+ }
4696
+ }
4697
+
4698
+ function _handleObj(stack, curStep) {
4699
+ // Initial object
4700
+ if (!curStep) {
4701
+ stack.push(OBJ);
4702
+ return;
4703
+ }
4704
+
4705
+ // New object as obj value
4706
+ if (curStep === OBJ_VAL) {
4707
+ stack.push(OBJ);
4708
+ return;
4709
+ }
4710
+
4711
+ // New object as array element
4712
+ if (curStep === ARR_VAL) {
4713
+ stack.push(OBJ);
4714
+ }
4715
+
4716
+ // New object as first array element
4717
+ if (curStep === ARR) {
4718
+ stack.push(OBJ);
4719
+ return;
4720
+ }
4721
+ }
4722
+
4723
+ function _handleArr(stack, curStep) {
4724
+ // Initial array
4725
+ if (!curStep) {
4726
+ stack.push(ARR);
4727
+ stack.push(ARR_VAL);
4728
+ return;
4729
+ }
4730
+
4731
+ // New array as obj value
4732
+ if (curStep === OBJ_VAL) {
4733
+ stack.push(ARR);
4734
+ stack.push(ARR_VAL);
4735
+ return;
4736
+ }
4737
+
4738
+ // New array as array element
4739
+ if (curStep === ARR_VAL) {
4740
+ stack.push(ARR);
4741
+ stack.push(ARR_VAL);
4742
+ }
4743
+
4744
+ // New array as first array element
4745
+ if (curStep === ARR) {
4746
+ stack.push(ARR);
4747
+ stack.push(ARR_VAL);
4748
+ return;
4749
+ }
4750
+ }
4751
+
4752
+ function _handleColon(stack, curStep) {
4753
+ if (curStep === OBJ_KEY) {
4754
+ stack.pop();
4755
+ stack.push(OBJ_VAL);
4756
+ }
4757
+ }
4758
+
4759
+ function _handleComma(stack, curStep) {
4760
+ // Comma after obj value
4761
+ if (curStep === OBJ_VAL) {
4762
+ stack.pop();
4763
+ return;
4764
+ }
4765
+ if (curStep === OBJ_VAL_COMPLETED) {
4766
+ // Pop OBJ_VAL_COMPLETED & OBJ_VAL
4767
+ stack.pop();
4768
+ stack.pop();
4769
+ return;
4770
+ }
4771
+
4772
+ // Comma after arr value
4773
+ if (curStep === ARR_VAL) {
4774
+ // do nothing - basically we'd pop ARR_VAL but add it right back
4775
+ return;
4776
+ }
4777
+
4778
+ if (curStep === ARR_VAL_COMPLETED) {
4779
+ // Pop ARR_VAL_COMPLETED
4780
+ stack.pop();
4781
+
4782
+ // basically we'd pop ARR_VAL but add it right back
4783
+ return;
4784
+ }
4785
+ }
4786
+
4787
+ function _handleObjClose(stack, curStep) {
4788
+ // Empty object {}
4789
+ if (curStep === OBJ) {
4790
+ stack.pop();
4791
+ }
4792
+
4793
+ // Object with element
4794
+ if (curStep === OBJ_VAL) {
4795
+ // Pop OBJ_VAL, OBJ
4796
+ stack.pop();
4797
+ stack.pop();
4798
+ }
4799
+
4800
+ // Obj with element
4801
+ if (curStep === OBJ_VAL_COMPLETED) {
4802
+ // Pop OBJ_VAL_COMPLETED, OBJ_VAL, OBJ
4803
+ stack.pop();
4804
+ stack.pop();
4805
+ stack.pop();
4806
+ }
4807
+
4808
+ // if was obj value, complete it
4809
+ if (stack[stack.length - 1] === OBJ_VAL) {
4810
+ stack.push(OBJ_VAL_COMPLETED);
4811
+ }
4812
+
4813
+ // if was arr value, complete it
4814
+ if (stack[stack.length - 1] === ARR_VAL) {
4815
+ stack.push(ARR_VAL_COMPLETED);
4816
+ }
4817
+ }
4818
+
4819
+ function _handleArrClose(stack, curStep) {
4820
+ // Empty array []
4821
+ if (curStep === ARR) {
4822
+ stack.pop();
4823
+ }
4824
+
4825
+ // Array with element
4826
+ if (curStep === ARR_VAL) {
4827
+ // Pop ARR_VAL, ARR
4828
+ stack.pop();
4829
+ stack.pop();
4830
+ }
4831
+
4832
+ // Array with element
4833
+ if (curStep === ARR_VAL_COMPLETED) {
4834
+ // Pop ARR_VAL_COMPLETED, ARR_VAL, ARR
4835
+ stack.pop();
4836
+ stack.pop();
4837
+ stack.pop();
4838
+ }
4839
+
4840
+ // if was obj value, complete it
4841
+ if (stack[stack.length - 1] === OBJ_VAL) {
4842
+ stack.push(OBJ_VAL_COMPLETED);
4843
+ }
4844
+
4845
+ // if was arr value, complete it
4846
+ if (stack[stack.length - 1] === ARR_VAL) {
4847
+ stack.push(ARR_VAL_COMPLETED);
4848
+ }
4849
+ }
4850
+
4851
+ function _isEscaped(str, pos) {
4852
+ const previousChar = str[pos - 1];
4853
+
4854
+ return previousChar === '\\' && !_isEscaped(str, pos - 1);
4855
+ }
4856
+
4857
+ /* eslint-disable max-lines */
4858
+
4859
+ /**
4860
+ * Takes an incomplete JSON string, and returns a hopefully valid JSON string.
4861
+ * Note that this _can_ fail, so you should check the return value is valid JSON.
4862
+ */
4863
+ function fixJson(incompleteJson) {
4864
+ const stack = evaluateJson(incompleteJson);
4865
+
4866
+ return completeJson(incompleteJson, stack);
4867
+ }
4868
+
4479
4869
  /** Get the size of a body. */
4480
4870
  function getBodySize(
4481
4871
  body,
@@ -4569,51 +4959,57 @@ function makeNetworkReplayBreadcrumb(
4569
4959
  return result;
4570
4960
  }
4571
4961
 
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;
4585
- }
4586
-
4587
4962
  /** Build the request or response part of a replay network breadcrumb. */
4588
4963
  function buildNetworkRequestOrResponse(
4964
+ headers,
4589
4965
  bodySize,
4590
4966
  body,
4591
4967
  ) {
4592
- if (!bodySize) {
4968
+ if (!bodySize && Object.keys(headers).length === 0) {
4593
4969
  return undefined;
4594
4970
  }
4595
4971
 
4972
+ if (!bodySize) {
4973
+ return {
4974
+ headers,
4975
+ };
4976
+ }
4977
+
4596
4978
  if (!body) {
4597
4979
  return {
4980
+ headers,
4598
4981
  size: bodySize,
4599
4982
  };
4600
4983
  }
4601
4984
 
4602
4985
  const info = {
4986
+ headers,
4603
4987
  size: bodySize,
4604
4988
  };
4605
4989
 
4606
- if (bodySize < NETWORK_BODY_MAX_SIZE) {
4607
- info.body = body;
4608
- } else {
4990
+ const { body: normalizedBody, warnings } = normalizeNetworkBody(body);
4991
+ info.body = normalizedBody;
4992
+ if (warnings.length > 0) {
4609
4993
  info._meta = {
4610
- errors: ['MAX_BODY_SIZE_EXCEEDED'],
4994
+ warnings,
4611
4995
  };
4612
4996
  }
4613
4997
 
4614
4998
  return info;
4615
4999
  }
4616
5000
 
5001
+ /** Filter a set of headers */
5002
+ function getAllowedHeaders(headers, allowedHeaders) {
5003
+ return Object.keys(headers).reduce((filteredHeaders, key) => {
5004
+ const normalizedKey = key.toLowerCase();
5005
+ // Avoid putting empty strings into the headers
5006
+ if (allowedHeaders.includes(normalizedKey) && headers[key]) {
5007
+ filteredHeaders[normalizedKey] = headers[key];
5008
+ }
5009
+ return filteredHeaders;
5010
+ }, {});
5011
+ }
5012
+
4617
5013
  function _serializeFormData(formData) {
4618
5014
  // This is a bit simplified, but gives us a decent estimate
4619
5015
  // This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'
@@ -4621,6 +5017,48 @@ function _serializeFormData(formData) {
4621
5017
  return new URLSearchParams(formData).toString();
4622
5018
  }
4623
5019
 
5020
+ function normalizeNetworkBody(body)
5021
+
5022
+ {
5023
+ if (!body || typeof body !== 'string') {
5024
+ return {
5025
+ body,
5026
+ warnings: [],
5027
+ };
5028
+ }
5029
+
5030
+ const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE;
5031
+
5032
+ if (_strIsProbablyJson(body)) {
5033
+ try {
5034
+ const json = exceedsSizeLimit ? fixJson(body.slice(0, NETWORK_BODY_MAX_SIZE)) : body;
5035
+ const normalizedBody = JSON.parse(json);
5036
+ return {
5037
+ body: normalizedBody,
5038
+ warnings: exceedsSizeLimit ? ['JSON_TRUNCATED'] : [],
5039
+ };
5040
+ } catch (e3) {
5041
+ return {
5042
+ body,
5043
+ warnings: ['INVALID_JSON'],
5044
+ };
5045
+ }
5046
+ }
5047
+
5048
+ return {
5049
+ body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,
5050
+ warnings: exceedsSizeLimit ? ['TEXT_TRUNCATED'] : [],
5051
+ };
5052
+ }
5053
+
5054
+ function _strIsProbablyJson(str) {
5055
+ const first = str[0];
5056
+ const last = str[str.length - 1];
5057
+
5058
+ // Simple check: If this does not start & end with {} or [], it's not JSON
5059
+ return (first === '[' && last === ']') || (first === '{' && last === '}');
5060
+ }
5061
+
4624
5062
  /**
4625
5063
  * Capture a fetch breadcrumb to a replay.
4626
5064
  * This adds additional data (where approriate).
@@ -4628,7 +5066,9 @@ function _serializeFormData(formData) {
4628
5066
  async function captureFetchBreadcrumbToReplay(
4629
5067
  breadcrumb,
4630
5068
  hint,
4631
- options,
5069
+ options
5070
+
5071
+ ,
4632
5072
  ) {
4633
5073
  try {
4634
5074
  const data = await _prepareFetchData(breadcrumb, hint, options);
@@ -4655,6 +5095,7 @@ function enrichFetchBreadcrumb(
4655
5095
 
4656
5096
  const body = _getFetchRequestArgBody(input);
4657
5097
  const reqSize = getBodySize(body, options.textEncoder);
5098
+
4658
5099
  const resSize = response ? parseContentLengthHeader(response.headers.get('content-length')) : undefined;
4659
5100
 
4660
5101
  if (reqSize !== undefined) {
@@ -4668,7 +5109,9 @@ function enrichFetchBreadcrumb(
4668
5109
  async function _prepareFetchData(
4669
5110
  breadcrumb,
4670
5111
  hint,
4671
- options,
5112
+ options
5113
+
5114
+ ,
4672
5115
  ) {
4673
5116
  const { startTimestamp, endTimestamp } = hint;
4674
5117
 
@@ -4695,34 +5138,44 @@ async function _prepareFetchData(
4695
5138
  }
4696
5139
 
4697
5140
  function _getRequestInfo(
4698
- { captureBodies },
5141
+ { captureBodies, requestHeaders },
4699
5142
  input,
4700
5143
  requestBodySize,
4701
5144
  ) {
5145
+ const headers = getRequestHeaders(input, requestHeaders);
5146
+
4702
5147
  if (!captureBodies) {
4703
- return buildNetworkRequestOrResponse(requestBodySize, undefined);
5148
+ return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);
4704
5149
  }
4705
5150
 
4706
5151
  // We only want to transmit string or string-like bodies
4707
5152
  const requestBody = _getFetchRequestArgBody(input);
4708
- const body = getNetworkBody(getBodyString(requestBody));
4709
- return buildNetworkRequestOrResponse(requestBodySize, body);
5153
+ const bodyStr = getBodyString(requestBody);
5154
+ return buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);
4710
5155
  }
4711
5156
 
4712
5157
  async function _getResponseInfo(
4713
- { captureBodies, textEncoder },
5158
+ {
5159
+ captureBodies,
5160
+ textEncoder,
5161
+ responseHeaders,
5162
+ }
5163
+
5164
+ ,
4714
5165
  response,
4715
5166
  responseBodySize,
4716
5167
  ) {
5168
+ const headers = getAllHeaders(response.headers, responseHeaders);
5169
+
4717
5170
  if (!captureBodies && responseBodySize !== undefined) {
4718
- return buildNetworkRequestOrResponse(responseBodySize, undefined);
5171
+ return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);
4719
5172
  }
4720
5173
 
4721
5174
  // Only clone the response if we need to
4722
5175
  try {
4723
5176
  // We have to clone this, as the body can only be read once
4724
5177
  const res = response.clone();
4725
- const { body, bodyText } = await _parseFetchBody(res);
5178
+ const bodyText = await _parseFetchBody(res);
4726
5179
 
4727
5180
  const size =
4728
5181
  bodyText && bodyText.length && responseBodySize === undefined
@@ -4730,35 +5183,22 @@ async function _getResponseInfo(
4730
5183
  : responseBodySize;
4731
5184
 
4732
5185
  if (captureBodies) {
4733
- return buildNetworkRequestOrResponse(size, body);
5186
+ return buildNetworkRequestOrResponse(headers, size, bodyText);
4734
5187
  }
4735
5188
 
4736
- return buildNetworkRequestOrResponse(size, undefined);
5189
+ return buildNetworkRequestOrResponse(headers, size, undefined);
4737
5190
  } catch (e) {
4738
5191
  // fallback
4739
- return buildNetworkRequestOrResponse(responseBodySize, undefined);
5192
+ return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);
4740
5193
  }
4741
5194
  }
4742
5195
 
4743
- async function _parseFetchBody(
4744
- response,
4745
- ) {
4746
- let bodyText;
4747
-
5196
+ async function _parseFetchBody(response) {
4748
5197
  try {
4749
- bodyText = await response.text();
5198
+ return await response.text();
4750
5199
  } catch (e2) {
4751
- return {};
4752
- }
4753
-
4754
- try {
4755
- const body = JSON.parse(bodyText);
4756
- return { body, bodyText };
4757
- } catch (e3) {
4758
- // just send bodyText
5200
+ return undefined;
4759
5201
  }
4760
-
4761
- return { bodyText, body: bodyText };
4762
5202
  }
4763
5203
 
4764
5204
  function _getFetchRequestArgBody(fetchArgs = []) {
@@ -4770,6 +5210,56 @@ function _getFetchRequestArgBody(fetchArgs = []) {
4770
5210
  return (fetchArgs[1] ).body;
4771
5211
  }
4772
5212
 
5213
+ function getAllHeaders(headers, allowedHeaders) {
5214
+ const allHeaders = {};
5215
+
5216
+ allowedHeaders.forEach(header => {
5217
+ if (headers.get(header)) {
5218
+ allHeaders[header] = headers.get(header) ;
5219
+ }
5220
+ });
5221
+
5222
+ return allHeaders;
5223
+ }
5224
+
5225
+ function getRequestHeaders(fetchArgs, allowedHeaders) {
5226
+ if (fetchArgs.length === 1 && typeof fetchArgs[0] !== 'string') {
5227
+ return getHeadersFromOptions(fetchArgs[0] , allowedHeaders);
5228
+ }
5229
+
5230
+ if (fetchArgs.length === 2) {
5231
+ return getHeadersFromOptions(fetchArgs[1] , allowedHeaders);
5232
+ }
5233
+
5234
+ return {};
5235
+ }
5236
+
5237
+ function getHeadersFromOptions(
5238
+ input,
5239
+ allowedHeaders,
5240
+ ) {
5241
+ if (!input) {
5242
+ return {};
5243
+ }
5244
+
5245
+ const headers = input.headers;
5246
+
5247
+ if (!headers) {
5248
+ return {};
5249
+ }
5250
+
5251
+ if (headers instanceof Headers) {
5252
+ return getAllHeaders(headers, allowedHeaders);
5253
+ }
5254
+
5255
+ // We do not support this, as it is not really documented (anymore?)
5256
+ if (Array.isArray(headers)) {
5257
+ return {};
5258
+ }
5259
+
5260
+ return getAllowedHeaders(headers, allowedHeaders);
5261
+ }
5262
+
4773
5263
  /**
4774
5264
  * Capture an XHR breadcrumb to a replay.
4775
5265
  * This adds additional data (where approriate).
@@ -4820,7 +5310,7 @@ function _prepareXhrData(
4820
5310
  hint,
4821
5311
  options,
4822
5312
  ) {
4823
- const { startTimestamp, endTimestamp, input } = hint;
5313
+ const { startTimestamp, endTimestamp, input, xhr } = hint;
4824
5314
 
4825
5315
  const {
4826
5316
  url,
@@ -4830,17 +5320,23 @@ function _prepareXhrData(
4830
5320
  response_body_size: responseBodySize,
4831
5321
  } = breadcrumb.data;
4832
5322
 
5323
+ const xhrInfo = xhr[utils.SENTRY_XHR_DATA_KEY];
5324
+ const requestHeaders = xhrInfo ? getAllowedHeaders(xhrInfo.request_headers, options.requestHeaders) : {};
5325
+ const responseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.responseHeaders);
5326
+
4833
5327
  if (!url) {
4834
5328
  return null;
4835
5329
  }
4836
5330
 
4837
5331
  const request = buildNetworkRequestOrResponse(
5332
+ requestHeaders,
4838
5333
  requestBodySize,
4839
- options.captureBodies ? getNetworkBody(getBodyString(input)) : undefined,
5334
+ options.captureBodies ? getBodyString(input) : undefined,
4840
5335
  );
4841
5336
  const response = buildNetworkRequestOrResponse(
5337
+ responseHeaders,
4842
5338
  responseBodySize,
4843
- options.captureBodies ? getNetworkBody(hint.xhr.responseText) : undefined,
5339
+ options.captureBodies ? hint.xhr.responseText : undefined,
4844
5340
  );
4845
5341
 
4846
5342
  return {
@@ -4854,6 +5350,20 @@ function _prepareXhrData(
4854
5350
  };
4855
5351
  }
4856
5352
 
5353
+ function getResponseHeaders(xhr) {
5354
+ const headers = xhr.getAllResponseHeaders();
5355
+
5356
+ if (!headers) {
5357
+ return {};
5358
+ }
5359
+
5360
+ return headers.split('\r\n').reduce((acc, line) => {
5361
+ const [key, value] = line.split(': ');
5362
+ acc[key.toLowerCase()] = value;
5363
+ return acc;
5364
+ }, {});
5365
+ }
5366
+
4857
5367
  /**
4858
5368
  * This method does two things:
4859
5369
  * - It enriches the regular XHR/fetch breadcrumbs with request/response size data
@@ -4869,7 +5379,7 @@ function handleNetworkBreadcrumbs(replay) {
4869
5379
  const options = {
4870
5380
  replay,
4871
5381
  textEncoder,
4872
- captureBodies: replay.getOptions()._experiments.captureNetworkBodies || false,
5382
+ ...replay.getExperimentalOptions().network,
4873
5383
  };
4874
5384
 
4875
5385
  if (client && client.on) {
@@ -5474,7 +5984,6 @@ async function sendReplayRequest({
5474
5984
  recordingData,
5475
5985
  replayId,
5476
5986
  segmentId: segment_id,
5477
- includeReplayStartTimestamp,
5478
5987
  eventContext,
5479
5988
  timestamp,
5480
5989
  session,
@@ -5501,7 +6010,7 @@ async function sendReplayRequest({
5501
6010
 
5502
6011
  const baseEvent = {
5503
6012
  type: REPLAY_EVENT_NAME,
5504
- ...(includeReplayStartTimestamp ? { replay_start_timestamp: initialTimestamp / 1000 } : {}),
6013
+ replay_start_timestamp: initialTimestamp / 1000,
5505
6014
  timestamp: timestamp / 1000,
5506
6015
  error_ids: errorIds,
5507
6016
  trace_ids: traceIds,
@@ -5760,6 +6269,8 @@ class ReplayContainer {
5760
6269
  this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {
5761
6270
  maxWait: this._options.flushMaxDelay,
5762
6271
  });
6272
+
6273
+ this._experimentalOptions = _getExperimentalOptions(options);
5763
6274
  }
5764
6275
 
5765
6276
  /** Get the event context. */
@@ -5782,6 +6293,15 @@ class ReplayContainer {
5782
6293
  return this._options;
5783
6294
  }
5784
6295
 
6296
+ /**
6297
+ * Get the experimental options.
6298
+ * THIS IS INTERNAL AND SUBJECT TO CHANGE!
6299
+ * @hidden
6300
+ */
6301
+ getExperimentalOptions() {
6302
+ return this._experimentalOptions;
6303
+ }
6304
+
5785
6305
  /**
5786
6306
  * Initializes the plugin.
5787
6307
  *
@@ -6383,7 +6903,6 @@ class ReplayContainer {
6383
6903
  replayId,
6384
6904
  recordingData,
6385
6905
  segmentId,
6386
- includeReplayStartTimestamp: segmentId === 0,
6387
6906
  eventContext,
6388
6907
  session: this.session,
6389
6908
  options: this.getOptions(),
@@ -6491,6 +7010,23 @@ class ReplayContainer {
6491
7010
  };}
6492
7011
  }
6493
7012
 
7013
+ function _getExperimentalOptions(options) {
7014
+ const requestHeaders = options._experiments.captureRequestHeaders || [];
7015
+ const responseHeaders = options._experiments.captureResponseHeaders || [];
7016
+ const captureBodies = options._experiments.captureNetworkBodies || false;
7017
+
7018
+ // Add defaults
7019
+ const defaultHeaders = ['content-length', 'content-type', 'accept'];
7020
+
7021
+ return {
7022
+ network: {
7023
+ captureBodies,
7024
+ requestHeaders: [...defaultHeaders, ...requestHeaders.map(header => header.toLowerCase())],
7025
+ responseHeaders: [...defaultHeaders, ...responseHeaders.map(header => header.toLowerCase())],
7026
+ },
7027
+ };
7028
+ }
7029
+
6494
7030
  function getOption(
6495
7031
  selectors,
6496
7032
  defaultSelectors,
@@ -6802,6 +7338,17 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
6802
7338
  return this._replay.flushImmediate();
6803
7339
  }
6804
7340
 
7341
+ /**
7342
+ * Get the current session ID.
7343
+ */
7344
+ getReplayId() {
7345
+ if (!this._replay || !this._replay.isEnabled()) {
7346
+ return;
7347
+ }
7348
+
7349
+ return this._replay.getSessionId();
7350
+ }
7351
+
6805
7352
  /** Setup the integration. */
6806
7353
  _setup() {
6807
7354
  // Client is not available in constructor, so we need to wait until setupOnce