@sentry/replay 0.6.10 → 0.6.11

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 (76) hide show
  1. package/README.md +10 -7
  2. package/dist/index.es.js +99 -47
  3. package/dist/index.js +98 -46
  4. package/dist/index.js.map +1 -1
  5. package/dist/types/src/index.d.ts +8 -4
  6. package/dist/types/src/session/Session.d.ts +4 -6
  7. package/dist/types/src/session/constants.d.ts +5 -0
  8. package/dist/types/src/session/createSession.d.ts +2 -13
  9. package/dist/types/src/session/fetchSession.d.ts +2 -1
  10. package/dist/types/src/session/getSession.d.ts +3 -11
  11. package/dist/types/src/types.d.ts +39 -13
  12. package/dist/types/src/util/isSampled.d.ts +1 -1
  13. package/package.json +1 -1
  14. package/dist/config/types/jest.config.d.ts +0 -3
  15. package/dist/config/types/jest.setup.d.ts +0 -32
  16. package/dist/config/types/src/blockAllMedia.test.d.ts +0 -1
  17. package/dist/config/types/src/coreHandlers/getBreadcrumbHandler.d.ts +0 -3
  18. package/dist/config/types/src/coreHandlers/getSpanHandler.d.ts +0 -5
  19. package/dist/config/types/src/coreHandlers/handleDom.d.ts +0 -1
  20. package/dist/config/types/src/coreHandlers/handleFetch.d.ts +0 -19
  21. package/dist/config/types/src/coreHandlers/handleFetch.test.d.ts +0 -1
  22. package/dist/config/types/src/coreHandlers/handleHistory.d.ts +0 -7
  23. package/dist/config/types/src/coreHandlers/handleScope-unit.test.d.ts +0 -1
  24. package/dist/config/types/src/coreHandlers/handleScope.d.ts +0 -2
  25. package/dist/config/types/src/coreHandlers/handleScope.test.d.ts +0 -1
  26. package/dist/config/types/src/coreHandlers/handleXhr.d.ts +0 -21
  27. package/dist/config/types/src/createPerformanceEntry.d.ts +0 -43
  28. package/dist/config/types/src/createPerformanceEntry.test.d.ts +0 -1
  29. package/dist/config/types/src/eventBuffer.d.ts +0 -45
  30. package/dist/config/types/src/eventBuffer.test.d.ts +0 -1
  31. package/dist/config/types/src/flags.d.ts +0 -2
  32. package/dist/config/types/src/flush.test.d.ts +0 -1
  33. package/dist/config/types/src/index-captureOnlyOnError.test.d.ts +0 -1
  34. package/dist/config/types/src/index-noSticky.test.d.ts +0 -1
  35. package/dist/config/types/src/index-sampling.test.d.ts +0 -1
  36. package/dist/config/types/src/index.d.ts +0 -289
  37. package/dist/config/types/src/index.test.d.ts +0 -1
  38. package/dist/config/types/src/multiple-instances.test.d.ts +0 -1
  39. package/dist/config/types/src/session/Session.d.ts +0 -63
  40. package/dist/config/types/src/session/Session.test.d.ts +0 -1
  41. package/dist/config/types/src/session/constants.d.ts +0 -6
  42. package/dist/config/types/src/session/createSession.d.ts +0 -19
  43. package/dist/config/types/src/session/createSession.test.d.ts +0 -1
  44. package/dist/config/types/src/session/deleteSession.d.ts +0 -4
  45. package/dist/config/types/src/session/deleteSession.test.d.ts +0 -1
  46. package/dist/config/types/src/session/fetchSession.d.ts +0 -5
  47. package/dist/config/types/src/session/fetchSession.test.d.ts +0 -1
  48. package/dist/config/types/src/session/getSession.d.ts +0 -28
  49. package/dist/config/types/src/session/getSession.test.d.ts +0 -1
  50. package/dist/config/types/src/session/index.d.ts +0 -1
  51. package/dist/config/types/src/session/saveSession.d.ts +0 -2
  52. package/dist/config/types/src/session/saveSession.test.d.ts +0 -1
  53. package/dist/config/types/src/stop.test.d.ts +0 -1
  54. package/dist/config/types/src/types.d.ts +0 -105
  55. package/dist/config/types/src/util/addInternalBreadcrumb.d.ts +0 -5
  56. package/dist/config/types/src/util/captureInternalException.d.ts +0 -4
  57. package/dist/config/types/src/util/createBreadcrumb.d.ts +0 -4
  58. package/dist/config/types/src/util/createPayload.d.ts +0 -5
  59. package/dist/config/types/src/util/dedupePerformanceEntries.d.ts +0 -10
  60. package/dist/config/types/src/util/dedupePerformanceEntries.test.d.ts +0 -1
  61. package/dist/config/types/src/util/isExpired.d.ts +0 -5
  62. package/dist/config/types/src/util/isExpired.test.d.ts +0 -1
  63. package/dist/config/types/src/util/isIngestHost.d.ts +0 -4
  64. package/dist/config/types/src/util/isInternal.d.ts +0 -5
  65. package/dist/config/types/src/util/isSampled.d.ts +0 -7
  66. package/dist/config/types/src/util/isSampled.test.d.ts +0 -1
  67. package/dist/config/types/src/util/isSessionExpired.d.ts +0 -5
  68. package/dist/config/types/src/util/isSessionExpired.test.d.ts +0 -1
  69. package/dist/config/types/src/util/logger.d.ts +0 -12
  70. package/dist/config/types/src/util/supportsSendBeacon.d.ts +0 -4
  71. package/dist/config/types/test/fixtures/performanceEntry/lcp.d.ts +0 -1
  72. package/dist/config/types/test/fixtures/performanceEntry/navigation.d.ts +0 -1
  73. package/dist/config/types/test/fixtures/performanceEntry/resource.d.ts +0 -1
  74. package/dist/config/types/test/index.d.ts +0 -3
  75. package/dist/config/types/test/mocks/mockRrweb.d.ts +0 -15
  76. package/dist/config/types/test/mocks/mockSdk.d.ts +0 -10
package/README.md CHANGED
@@ -35,7 +35,11 @@ Sentry.init({
35
35
  new Replay({
36
36
  // This sets the sample rate to be 10%. You may want this to be 100% while
37
37
  // in development and sample at a lower rate in production
38
- replaysSamplingRate: 0.1,
38
+ sessionSampleRate: 0.1,
39
+
40
+ // If the entire session is not sampled, use the below sample rate to sample
41
+ // sessions when an error occurs.
42
+ errorSampleRate: 1.0,
39
43
 
40
44
  // Mask all text content with asterisks (*). Passes text
41
45
  // content through to `maskTextFn` before sending to server.
@@ -79,12 +83,11 @@ replay.stop(); // Stop recording
79
83
 
80
84
  ### General Configuration
81
85
 
82
- | key | type | default | description |
83
- | ------------------- | ------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
84
- | captureOnlyOnError | boolean | `false` | Only capture the recording when an error happens. The recording is currently limited to up to the last 60 seconds before the error occurs and only records up to the error. |
85
- | initialFlushDelay | number | `5000` | The amount of time to wait (in ms) before sending the initial recording payload. This helps drop recordings where users visit and close the page quickly. |
86
- | replaysSamplingRate | number | `1.0` | The rate at which to sample replays. (1.0 will collect all replays, 0 will collect no replays). |
87
- | stickySession | boolean | `true` | Keep track of the user across page loads. Note a single user using multiple tabs will result in multiple sessions. Closing a tab will result in the session being closed as well. |
86
+ | key | type | default | description |
87
+ | ------------------- | ------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
88
+ | sessionSampleRate | number | `0.1` | The sample rate for all sessions, which will capture the entirety from when a user begins a session until the session ends. (1.0 will collect all replays, 0 will collect no replays) |
89
+ | errorSampleRate | number | `1.0` | If a session isn't already being recorded via `sessionSampleRate`, based on `errorSampleRate` the SDK will send the captured replay when an error occurs. (1.0 capturing all sessions with an error, and 0 capturing none). |
90
+ | stickySession | boolean | `true` | Keep track of the user across page loads. Note a single user using multiple tabs will result in multiple sessions. Closing a tab will result in the session being closed as well. |
88
91
 
89
92
  ### Privacy Configuration
90
93
 
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
1
- import { getCurrentHub, captureException, addBreadcrumb, addGlobalEventProcessor, setContext, getEnvelopeEndpointWithUrlEncodedAuth } from '@sentry/core';
1
+ import { getCurrentHub, addBreadcrumb, captureException, addGlobalEventProcessor, setContext, getEnvelopeEndpointWithUrlEncodedAuth } from '@sentry/core';
2
2
  import { htmlTreeAsString, logger as logger$1, uuid4, browserPerformanceTimeOrigin, addInstrumentationHandler, createEnvelope, serializeEnvelope } from '@sentry/utils';
3
3
  import debounce from 'lodash.debounce';
4
4
  import { record, EventType } from 'rrweb';
@@ -252,6 +252,11 @@ var SESSION_IDLE_DURATION = 300000; // 5 minutes in ms
252
252
  var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
253
253
  // The maximum length of a session
254
254
  var MAX_SESSION_LIFE = 1800000; // 30 minutes
255
+ /**
256
+ * Defaults for sampling rates
257
+ */
258
+ var DEFAULT_SESSION_SAMPLE_RATE = 0.1;
259
+ var DEFAULT_ERROR_SAMPLE_RATE = 1.0;
255
260
 
256
261
  /**
257
262
  * Deletes a session from storage
@@ -330,6 +335,9 @@ function saveSession(session) {
330
335
  * 0.0 = 0% sampling
331
336
  */
332
337
  function isSampled(sampleRate) {
338
+ if (sampleRate === undefined) {
339
+ return false;
340
+ }
333
341
  // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)
334
342
  return Math.random() < sampleRate;
335
343
  }
@@ -337,14 +345,15 @@ function isSampled(sampleRate) {
337
345
  var Session = /** @class */ (function () {
338
346
  function Session(session, _a) {
339
347
  if (session === void 0) { session = {}; }
340
- var _b = _a === void 0 ? {} : _a, _c = _b.stickySession, stickySession = _c === void 0 ? false : _c, _d = _b.samplingRate, samplingRate = _d === void 0 ? 1.0 : _d;
341
- var _e, _f, _g, _h;
348
+ var stickySession = _a.stickySession, sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate;
349
+ var _b, _c, _d, _e;
342
350
  var now = new Date().getTime();
343
351
  this._id = session.id || uuid4();
344
- this._started = (_e = session.started) !== null && _e !== void 0 ? _e : now;
345
- this._lastActivity = (_f = session.lastActivity) !== null && _f !== void 0 ? _f : now;
346
- this._segmentId = (_g = session.segmentId) !== null && _g !== void 0 ? _g : 0;
347
- this._sampled = (_h = session.sampled) !== null && _h !== void 0 ? _h : isSampled(samplingRate);
352
+ this._started = (_b = session.started) !== null && _b !== void 0 ? _b : now;
353
+ this._lastActivity = (_c = session.lastActivity) !== null && _c !== void 0 ? _c : now;
354
+ this._segmentId = (_d = session.segmentId) !== null && _d !== void 0 ? _d : 0;
355
+ this._sampled =
356
+ (_e = session.sampled) !== null && _e !== void 0 ? _e : (isSampled(sessionSampleRate) || isSampled(errorSampleRate));
348
357
  this.options = {
349
358
  stickySession: stickySession,
350
359
  };
@@ -427,8 +436,12 @@ var Session = /** @class */ (function () {
427
436
  * one of these Sentry events per "replay session".
428
437
  */
429
438
  function createSession(_a) {
430
- var _b = _a.stickySession, stickySession = _b === void 0 ? false : _b, _c = _a.samplingRate, samplingRate = _c === void 0 ? 1.0 : _c;
431
- var session = new Session(undefined, { stickySession: stickySession, samplingRate: samplingRate });
439
+ var sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate, _b = _a.stickySession, stickySession = _b === void 0 ? false : _b;
440
+ var session = new Session(undefined, {
441
+ stickySession: stickySession,
442
+ errorSampleRate: errorSampleRate,
443
+ sessionSampleRate: sessionSampleRate,
444
+ });
432
445
  logger.log("Creating new session: ".concat(session.id));
433
446
  if (stickySession) {
434
447
  saveSession(session);
@@ -436,20 +449,11 @@ function createSession(_a) {
436
449
  return session;
437
450
  }
438
451
 
439
- /**
440
- * Captures exceptions to Sentry only when it occurs on sentry.io
441
- */
442
- function captureInternalException(err) {
443
- if (!isInternal()) {
444
- return;
445
- }
446
- captureException(err);
447
- }
448
-
449
452
  /**
450
453
  * Fetches a session from storage
451
454
  */
452
- function fetchSession() {
455
+ function fetchSession(_a) {
456
+ var sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate;
453
457
  var hasSessionStorage = 'sessionStorage' in window;
454
458
  if (!hasSessionStorage) {
455
459
  return null;
@@ -460,16 +464,13 @@ function fetchSession() {
460
464
  }
461
465
  try {
462
466
  var sessionObj = JSON.parse(sessionStringFromStorage);
463
- // NOTE: This shouldn't happen
464
- if (sessionObj.segmentId === 0) {
465
- captureInternalException(new Error('Session storage object with segmentId = 0'));
466
- }
467
+ // TODO: It's unexpected, but people seem to encounter `sessionObj.segmentId === 0`
467
468
  return new Session(sessionObj,
468
469
  // We are assuming that if there is a saved item, then the session is sticky,
469
470
  // however this could break down if we used a different storage mechanism (e.g. localstorage)
470
- { stickySession: true });
471
+ { stickySession: true, sessionSampleRate: sessionSampleRate, errorSampleRate: errorSampleRate });
471
472
  }
472
- catch (_a) {
473
+ catch (_b) {
473
474
  return null;
474
475
  }
475
476
  }
@@ -478,9 +479,10 @@ function fetchSession() {
478
479
  * Get or create a session
479
480
  */
480
481
  function getSession(_a) {
481
- var expiry = _a.expiry, currentSession = _a.currentSession, stickySession = _a.stickySession, samplingRate = _a.samplingRate;
482
+ var expiry = _a.expiry, currentSession = _a.currentSession, stickySession = _a.stickySession, sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate;
482
483
  // If session exists and is passed, use it instead of always hitting session storage
483
- var session = currentSession || (stickySession && fetchSession());
484
+ var session = currentSession ||
485
+ (stickySession && fetchSession({ sessionSampleRate: sessionSampleRate, errorSampleRate: errorSampleRate }));
484
486
  if (session) {
485
487
  // If there is a session, check if it is valid (e.g. "last activity" time
486
488
  // should be within the "session idle time", and "session started" time is
@@ -494,7 +496,11 @@ function getSession(_a) {
494
496
  }
495
497
  // Otherwise continue to create a new session
496
498
  }
497
- var newSession = createSession({ stickySession: stickySession, samplingRate: samplingRate });
499
+ var newSession = createSession({
500
+ stickySession: stickySession,
501
+ sessionSampleRate: sessionSampleRate,
502
+ errorSampleRate: errorSampleRate,
503
+ });
498
504
  return { type: 'new', session: newSession };
499
505
  }
500
506
 
@@ -509,6 +515,16 @@ function addInternalBreadcrumb(arg) {
509
515
  addBreadcrumb(__assign({ category: category || 'console', level: level || 'debug', message: "[debug]: ".concat(message) }, rest));
510
516
  }
511
517
 
518
+ /**
519
+ * Captures exceptions to Sentry only when it occurs on sentry.io
520
+ */
521
+ function captureInternalException(err) {
522
+ if (!isInternal()) {
523
+ return;
524
+ }
525
+ captureException(err);
526
+ }
527
+
512
528
  function createPayload(_a) {
513
529
  var events = _a.events, headers = _a.headers;
514
530
  var payloadWithSequence;
@@ -909,7 +925,7 @@ var Replay = /** @class */ (function () {
909
925
  function Replay(_a) {
910
926
  if (_a === void 0) { _a = {}; }
911
927
  var _this = this;
912
- var _b = _a.flushMinDelay, flushMinDelay = _b === void 0 ? 5000 : _b, _c = _a.flushMaxDelay, flushMaxDelay = _c === void 0 ? 15000 : _c, _d = _a.initialFlushDelay, initialFlushDelay = _d === void 0 ? 5000 : _d, _e = _a.stickySession, stickySession = _e === void 0 ? true : _e, _f = _a.useCompression, useCompression = _f === void 0 ? true : _f, _g = _a.captureOnlyOnError, captureOnlyOnError = _g === void 0 ? false : _g, _h = _a.replaysSamplingRate, replaysSamplingRate = _h === void 0 ? 1.0 : _h, _j = _a.maskAllText, maskAllText = _j === void 0 ? true : _j, _k = _a.maskAllInputs, maskAllInputs = _k === void 0 ? true : _k, _l = _a.blockAllMedia, blockAllMedia = _l === void 0 ? true : _l, _m = _a.blockClass, blockClass = _m === void 0 ? 'sentry-block' : _m, _o = _a.ignoreClass, ignoreClass = _o === void 0 ? 'sentry-ignore' : _o, _p = _a.maskTextClass, maskTextClass = _p === void 0 ? 'sentry-mask' : _p, _q = _a.blockSelector, blockSelector = _q === void 0 ? '[data-sentry-block]' : _q, recordingOptions = __rest(_a, ["flushMinDelay", "flushMaxDelay", "initialFlushDelay", "stickySession", "useCompression", "captureOnlyOnError", "replaysSamplingRate", "maskAllText", "maskAllInputs", "blockAllMedia", "blockClass", "ignoreClass", "maskTextClass", "blockSelector"]);
928
+ var _b = _a.flushMinDelay, flushMinDelay = _b === void 0 ? 5000 : _b, _c = _a.flushMaxDelay, flushMaxDelay = _c === void 0 ? 15000 : _c, _d = _a.initialFlushDelay, initialFlushDelay = _d === void 0 ? 5000 : _d, _e = _a.stickySession, stickySession = _e === void 0 ? true : _e, _f = _a.useCompression, useCompression = _f === void 0 ? true : _f, _g = _a.sessionSampleRate, sessionSampleRate = _g === void 0 ? DEFAULT_SESSION_SAMPLE_RATE : _g, _h = _a.errorSampleRate, errorSampleRate = _h === void 0 ? DEFAULT_ERROR_SAMPLE_RATE : _h, _j = _a.maskAllText, maskAllText = _j === void 0 ? true : _j, _k = _a.maskAllInputs, maskAllInputs = _k === void 0 ? true : _k, _l = _a.blockAllMedia, blockAllMedia = _l === void 0 ? true : _l, _m = _a.blockClass, blockClass = _m === void 0 ? 'sentry-block' : _m, _o = _a.ignoreClass, ignoreClass = _o === void 0 ? 'sentry-ignore' : _o, _p = _a.maskTextClass, maskTextClass = _p === void 0 ? 'sentry-mask' : _p, _q = _a.blockSelector, blockSelector = _q === void 0 ? '[data-sentry-block]' : _q, replaysSamplingRate = _a.replaysSamplingRate, captureOnlyOnError = _a.captureOnlyOnError, recordingOptions = __rest(_a, ["flushMinDelay", "flushMaxDelay", "initialFlushDelay", "stickySession", "useCompression", "sessionSampleRate", "errorSampleRate", "maskAllText", "maskAllInputs", "blockAllMedia", "blockClass", "ignoreClass", "maskTextClass", "blockSelector", "replaysSamplingRate", "captureOnlyOnError"]);
913
929
  /**
914
930
  * @inheritDoc
915
931
  */
@@ -931,12 +947,16 @@ var Replay = /** @class */ (function () {
931
947
  */
932
948
  this.isEnabled = false;
933
949
  /**
934
- *
935
950
  * Paused is a state where:
936
951
  * - DOM Recording is not listening at all
937
952
  * - Nothing will be added to event buffer (e.g. core SDK events)
938
953
  */
939
954
  this.isPaused = false;
955
+ /**
956
+ * Integration will wait until an error occurs before creating and sending a
957
+ * replay.
958
+ */
959
+ this.waitForError = false;
940
960
  /**
941
961
  * Have we attached listeners to the core SDK?
942
962
  * Note we have to track this as there is no way to remove instrumentation handlers.
@@ -981,13 +1001,28 @@ var Replay = /** @class */ (function () {
981
1001
  message: "Tagging event (".concat(event.event_id, ") - ").concat(event.message, " - ").concat((exc === null || exc === void 0 ? void 0 : exc.type) || 'Unknown', ": ").concat((exc === null || exc === void 0 ? void 0 : exc.value) || 'n/a'),
982
1002
  });
983
1003
  // Need to be very careful that this does not cause an infinite loop
984
- if (_this.options.captureOnlyOnError &&
1004
+ if (_this.waitForError &&
985
1005
  event.exception &&
986
- event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because other we could loop indefinitely with trying to capture replay and failing
1006
+ event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because otherwise we could loop indefinitely with trying to capture replay and failing
987
1007
  ) {
988
- // TODO: Do we continue to record after?
989
- // TODO: What happens if another error happens? Do we record in the same session?
990
- setTimeout(function () { return _this.flushImmediate(); });
1008
+ setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
1009
+ return __generator(this, function (_a) {
1010
+ switch (_a.label) {
1011
+ case 0: return [4 /*yield*/, this.flushImmediate()];
1012
+ case 1:
1013
+ _a.sent();
1014
+ if (this.stopRecording) {
1015
+ this.stopRecording();
1016
+ // Reset all "capture on error" configuration before
1017
+ // starting a new recording
1018
+ delete this.recordingOptions.checkoutEveryNms;
1019
+ this.waitForError = false;
1020
+ this.startRecording();
1021
+ }
1022
+ return [2 /*return*/];
1023
+ }
1024
+ });
1025
+ }); });
991
1026
  }
992
1027
  return event;
993
1028
  };
@@ -1200,21 +1235,37 @@ var Replay = /** @class */ (function () {
1200
1235
  });
1201
1236
  }); };
1202
1237
  this.recordingOptions = __assign({ maskAllInputs: maskAllInputs, blockClass: blockClass, ignoreClass: ignoreClass, maskTextClass: maskTextClass, blockSelector: blockSelector }, recordingOptions);
1238
+ var usingDeprecatedReplaysSamplingRate = replaysSamplingRate !== undefined;
1239
+ var usingDeprecatedCaptureOnlyOnError = captureOnlyOnError !== undefined;
1203
1240
  this.options = {
1204
1241
  flushMinDelay: flushMinDelay,
1205
1242
  flushMaxDelay: flushMaxDelay,
1206
1243
  stickySession: stickySession,
1207
1244
  initialFlushDelay: initialFlushDelay,
1208
- captureOnlyOnError: captureOnlyOnError,
1209
- replaysSamplingRate: replaysSamplingRate,
1245
+ sessionSampleRate: usingDeprecatedReplaysSamplingRate
1246
+ ? replaysSamplingRate
1247
+ : sessionSampleRate,
1248
+ errorSampleRate: usingDeprecatedCaptureOnlyOnError
1249
+ ? 1.0
1250
+ : errorSampleRate,
1210
1251
  useCompression: useCompression,
1211
1252
  maskAllText: maskAllText,
1212
1253
  blockAllMedia: blockAllMedia,
1213
1254
  };
1214
- // Modify rrweb options to checkoutEveryNthSecond if this is defined, as we don't know when an error occurs, so we want to try to minimize the number of events captured.
1215
- if (this.options.captureOnlyOnError) {
1255
+ // Modify recording options to checkoutEveryNthSecond if this is defined, as we
1256
+ // don't know when an error will occur, so we need to keep a buffer of replay events.
1257
+ if (this.options.errorSampleRate > 0 &&
1258
+ this.options.sessionSampleRate < 1.0) {
1216
1259
  // Checkout every minute, meaning we only get up-to one minute of events before the error happens
1217
1260
  this.recordingOptions.checkoutEveryNms = 60000;
1261
+ this.waitForError = true;
1262
+ }
1263
+ // TODO(deprecated): Maintain backwards compatibility for alpha users
1264
+ if (usingDeprecatedCaptureOnlyOnError) {
1265
+ console.warn('[@sentry/replay]: The `captureOnlyOnError` option is deprecated! Please configure `errorSampleRate` instead.');
1266
+ }
1267
+ if (usingDeprecatedReplaysSamplingRate) {
1268
+ console.warn('[@sentry/replay]: The `replaysSamplingRate` option is deprecated! Please configure `sessionSampleRate` instead.');
1218
1269
  }
1219
1270
  if (this.options.maskAllText) {
1220
1271
  // `maskAllText` is a more user friendly option to configure
@@ -1347,7 +1398,8 @@ var Replay = /** @class */ (function () {
1347
1398
  expiry: expiry,
1348
1399
  stickySession: Boolean(this.options.stickySession),
1349
1400
  currentSession: this.session,
1350
- samplingRate: this.options.replaysSamplingRate,
1401
+ sessionSampleRate: this.options.sessionSampleRate,
1402
+ errorSampleRate: this.options.errorSampleRate,
1351
1403
  }), type = _d.type, session = _d.session;
1352
1404
  // If session was newly created (i.e. was not loaded from storage), then
1353
1405
  // enable flag to create the root replay
@@ -1446,11 +1498,11 @@ var Replay = /** @class */ (function () {
1446
1498
  * processing and hand back control to caller.
1447
1499
  */
1448
1500
  Replay.prototype.addUpdate = function (cb) {
1449
- // We need to always run `cb` (e.g. in the case of captureOnlyOnError == true)
1501
+ // We need to always run `cb` (e.g. in the case of `this.waitForError == true`)
1450
1502
  var cbResult = cb === null || cb === void 0 ? void 0 : cb();
1451
1503
  // If this option is turned on then we will only want to call `flush`
1452
1504
  // explicitly
1453
- if (this.options.captureOnlyOnError) {
1505
+ if (this.waitForError) {
1454
1506
  return;
1455
1507
  }
1456
1508
  // If callback is true, we do not want to continue with flushing -- the
@@ -1681,10 +1733,10 @@ var Replay = /** @class */ (function () {
1681
1733
  return false;
1682
1734
  };
1683
1735
  /**
1684
- * Only flush if `captureOnlyOnError` is false.
1736
+ * Only flush if `this.waitForError` is false.
1685
1737
  */
1686
1738
  Replay.prototype.conditionalFlush = function () {
1687
- if (this.options.captureOnlyOnError) {
1739
+ if (this.waitForError) {
1688
1740
  return;
1689
1741
  }
1690
1742
  this.flushImmediate();
@@ -1783,7 +1835,7 @@ var Replay = /** @class */ (function () {
1783
1835
  Replay.prototype.flushImmediate = function () {
1784
1836
  this.debouncedFlush();
1785
1837
  // `.flush` is provided by lodash.debounce
1786
- this.debouncedFlush.flush();
1838
+ return this.debouncedFlush.flush();
1787
1839
  };
1788
1840
  /**
1789
1841
  * Send replay attachment using `fetch()`
@@ -1807,7 +1859,7 @@ var Replay = /** @class */ (function () {
1807
1859
  timestamp = new Date().getTime();
1808
1860
  sdkInfo = {
1809
1861
  name: 'sentry.javascript.integration.replay',
1810
- version: "0.6.10",
1862
+ version: "0.6.11",
1811
1863
  };
1812
1864
  return [4 /*yield*/, new Promise(function (resolve) {
1813
1865
  var _a;
package/dist/index.js CHANGED
@@ -260,6 +260,11 @@ var SESSION_IDLE_DURATION = 300000; // 5 minutes in ms
260
260
  var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
261
261
  // The maximum length of a session
262
262
  var MAX_SESSION_LIFE = 1800000; // 30 minutes
263
+ /**
264
+ * Defaults for sampling rates
265
+ */
266
+ var DEFAULT_SESSION_SAMPLE_RATE = 0.1;
267
+ var DEFAULT_ERROR_SAMPLE_RATE = 1.0;
263
268
 
264
269
  /**
265
270
  * Deletes a session from storage
@@ -338,6 +343,9 @@ function saveSession(session) {
338
343
  * 0.0 = 0% sampling
339
344
  */
340
345
  function isSampled(sampleRate) {
346
+ if (sampleRate === undefined) {
347
+ return false;
348
+ }
341
349
  // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)
342
350
  return Math.random() < sampleRate;
343
351
  }
@@ -345,14 +353,15 @@ function isSampled(sampleRate) {
345
353
  var Session = /** @class */ (function () {
346
354
  function Session(session, _a) {
347
355
  if (session === void 0) { session = {}; }
348
- var _b = _a === void 0 ? {} : _a, _c = _b.stickySession, stickySession = _c === void 0 ? false : _c, _d = _b.samplingRate, samplingRate = _d === void 0 ? 1.0 : _d;
349
- var _e, _f, _g, _h;
356
+ var stickySession = _a.stickySession, sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate;
357
+ var _b, _c, _d, _e;
350
358
  var now = new Date().getTime();
351
359
  this._id = session.id || utils.uuid4();
352
- this._started = (_e = session.started) !== null && _e !== void 0 ? _e : now;
353
- this._lastActivity = (_f = session.lastActivity) !== null && _f !== void 0 ? _f : now;
354
- this._segmentId = (_g = session.segmentId) !== null && _g !== void 0 ? _g : 0;
355
- this._sampled = (_h = session.sampled) !== null && _h !== void 0 ? _h : isSampled(samplingRate);
360
+ this._started = (_b = session.started) !== null && _b !== void 0 ? _b : now;
361
+ this._lastActivity = (_c = session.lastActivity) !== null && _c !== void 0 ? _c : now;
362
+ this._segmentId = (_d = session.segmentId) !== null && _d !== void 0 ? _d : 0;
363
+ this._sampled =
364
+ (_e = session.sampled) !== null && _e !== void 0 ? _e : (isSampled(sessionSampleRate) || isSampled(errorSampleRate));
356
365
  this.options = {
357
366
  stickySession: stickySession,
358
367
  };
@@ -435,8 +444,12 @@ var Session = /** @class */ (function () {
435
444
  * one of these Sentry events per "replay session".
436
445
  */
437
446
  function createSession(_a) {
438
- var _b = _a.stickySession, stickySession = _b === void 0 ? false : _b, _c = _a.samplingRate, samplingRate = _c === void 0 ? 1.0 : _c;
439
- var session = new Session(undefined, { stickySession: stickySession, samplingRate: samplingRate });
447
+ var sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate, _b = _a.stickySession, stickySession = _b === void 0 ? false : _b;
448
+ var session = new Session(undefined, {
449
+ stickySession: stickySession,
450
+ errorSampleRate: errorSampleRate,
451
+ sessionSampleRate: sessionSampleRate,
452
+ });
440
453
  logger.log("Creating new session: ".concat(session.id));
441
454
  if (stickySession) {
442
455
  saveSession(session);
@@ -444,20 +457,11 @@ function createSession(_a) {
444
457
  return session;
445
458
  }
446
459
 
447
- /**
448
- * Captures exceptions to Sentry only when it occurs on sentry.io
449
- */
450
- function captureInternalException(err) {
451
- if (!isInternal()) {
452
- return;
453
- }
454
- core.captureException(err);
455
- }
456
-
457
460
  /**
458
461
  * Fetches a session from storage
459
462
  */
460
- function fetchSession() {
463
+ function fetchSession(_a) {
464
+ var sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate;
461
465
  var hasSessionStorage = 'sessionStorage' in window;
462
466
  if (!hasSessionStorage) {
463
467
  return null;
@@ -468,16 +472,13 @@ function fetchSession() {
468
472
  }
469
473
  try {
470
474
  var sessionObj = JSON.parse(sessionStringFromStorage);
471
- // NOTE: This shouldn't happen
472
- if (sessionObj.segmentId === 0) {
473
- captureInternalException(new Error('Session storage object with segmentId = 0'));
474
- }
475
+ // TODO: It's unexpected, but people seem to encounter `sessionObj.segmentId === 0`
475
476
  return new Session(sessionObj,
476
477
  // We are assuming that if there is a saved item, then the session is sticky,
477
478
  // however this could break down if we used a different storage mechanism (e.g. localstorage)
478
- { stickySession: true });
479
+ { stickySession: true, sessionSampleRate: sessionSampleRate, errorSampleRate: errorSampleRate });
479
480
  }
480
- catch (_a) {
481
+ catch (_b) {
481
482
  return null;
482
483
  }
483
484
  }
@@ -486,9 +487,10 @@ function fetchSession() {
486
487
  * Get or create a session
487
488
  */
488
489
  function getSession(_a) {
489
- var expiry = _a.expiry, currentSession = _a.currentSession, stickySession = _a.stickySession, samplingRate = _a.samplingRate;
490
+ var expiry = _a.expiry, currentSession = _a.currentSession, stickySession = _a.stickySession, sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate;
490
491
  // If session exists and is passed, use it instead of always hitting session storage
491
- var session = currentSession || (stickySession && fetchSession());
492
+ var session = currentSession ||
493
+ (stickySession && fetchSession({ sessionSampleRate: sessionSampleRate, errorSampleRate: errorSampleRate }));
492
494
  if (session) {
493
495
  // If there is a session, check if it is valid (e.g. "last activity" time
494
496
  // should be within the "session idle time", and "session started" time is
@@ -502,7 +504,11 @@ function getSession(_a) {
502
504
  }
503
505
  // Otherwise continue to create a new session
504
506
  }
505
- var newSession = createSession({ stickySession: stickySession, samplingRate: samplingRate });
507
+ var newSession = createSession({
508
+ stickySession: stickySession,
509
+ sessionSampleRate: sessionSampleRate,
510
+ errorSampleRate: errorSampleRate,
511
+ });
506
512
  return { type: 'new', session: newSession };
507
513
  }
508
514
 
@@ -517,6 +523,16 @@ function addInternalBreadcrumb(arg) {
517
523
  core.addBreadcrumb(__assign({ category: category || 'console', level: level || 'debug', message: "[debug]: ".concat(message) }, rest));
518
524
  }
519
525
 
526
+ /**
527
+ * Captures exceptions to Sentry only when it occurs on sentry.io
528
+ */
529
+ function captureInternalException(err) {
530
+ if (!isInternal()) {
531
+ return;
532
+ }
533
+ core.captureException(err);
534
+ }
535
+
520
536
  function createPayload(_a) {
521
537
  var events = _a.events, headers = _a.headers;
522
538
  var payloadWithSequence;
@@ -917,7 +933,7 @@ var Replay = /** @class */ (function () {
917
933
  function Replay(_a) {
918
934
  if (_a === void 0) { _a = {}; }
919
935
  var _this = this;
920
- var _b = _a.flushMinDelay, flushMinDelay = _b === void 0 ? 5000 : _b, _c = _a.flushMaxDelay, flushMaxDelay = _c === void 0 ? 15000 : _c, _d = _a.initialFlushDelay, initialFlushDelay = _d === void 0 ? 5000 : _d, _e = _a.stickySession, stickySession = _e === void 0 ? true : _e, _f = _a.useCompression, useCompression = _f === void 0 ? true : _f, _g = _a.captureOnlyOnError, captureOnlyOnError = _g === void 0 ? false : _g, _h = _a.replaysSamplingRate, replaysSamplingRate = _h === void 0 ? 1.0 : _h, _j = _a.maskAllText, maskAllText = _j === void 0 ? true : _j, _k = _a.maskAllInputs, maskAllInputs = _k === void 0 ? true : _k, _l = _a.blockAllMedia, blockAllMedia = _l === void 0 ? true : _l, _m = _a.blockClass, blockClass = _m === void 0 ? 'sentry-block' : _m, _o = _a.ignoreClass, ignoreClass = _o === void 0 ? 'sentry-ignore' : _o, _p = _a.maskTextClass, maskTextClass = _p === void 0 ? 'sentry-mask' : _p, _q = _a.blockSelector, blockSelector = _q === void 0 ? '[data-sentry-block]' : _q, recordingOptions = __rest(_a, ["flushMinDelay", "flushMaxDelay", "initialFlushDelay", "stickySession", "useCompression", "captureOnlyOnError", "replaysSamplingRate", "maskAllText", "maskAllInputs", "blockAllMedia", "blockClass", "ignoreClass", "maskTextClass", "blockSelector"]);
936
+ var _b = _a.flushMinDelay, flushMinDelay = _b === void 0 ? 5000 : _b, _c = _a.flushMaxDelay, flushMaxDelay = _c === void 0 ? 15000 : _c, _d = _a.initialFlushDelay, initialFlushDelay = _d === void 0 ? 5000 : _d, _e = _a.stickySession, stickySession = _e === void 0 ? true : _e, _f = _a.useCompression, useCompression = _f === void 0 ? true : _f, _g = _a.sessionSampleRate, sessionSampleRate = _g === void 0 ? DEFAULT_SESSION_SAMPLE_RATE : _g, _h = _a.errorSampleRate, errorSampleRate = _h === void 0 ? DEFAULT_ERROR_SAMPLE_RATE : _h, _j = _a.maskAllText, maskAllText = _j === void 0 ? true : _j, _k = _a.maskAllInputs, maskAllInputs = _k === void 0 ? true : _k, _l = _a.blockAllMedia, blockAllMedia = _l === void 0 ? true : _l, _m = _a.blockClass, blockClass = _m === void 0 ? 'sentry-block' : _m, _o = _a.ignoreClass, ignoreClass = _o === void 0 ? 'sentry-ignore' : _o, _p = _a.maskTextClass, maskTextClass = _p === void 0 ? 'sentry-mask' : _p, _q = _a.blockSelector, blockSelector = _q === void 0 ? '[data-sentry-block]' : _q, replaysSamplingRate = _a.replaysSamplingRate, captureOnlyOnError = _a.captureOnlyOnError, recordingOptions = __rest(_a, ["flushMinDelay", "flushMaxDelay", "initialFlushDelay", "stickySession", "useCompression", "sessionSampleRate", "errorSampleRate", "maskAllText", "maskAllInputs", "blockAllMedia", "blockClass", "ignoreClass", "maskTextClass", "blockSelector", "replaysSamplingRate", "captureOnlyOnError"]);
921
937
  /**
922
938
  * @inheritDoc
923
939
  */
@@ -939,12 +955,16 @@ var Replay = /** @class */ (function () {
939
955
  */
940
956
  this.isEnabled = false;
941
957
  /**
942
- *
943
958
  * Paused is a state where:
944
959
  * - DOM Recording is not listening at all
945
960
  * - Nothing will be added to event buffer (e.g. core SDK events)
946
961
  */
947
962
  this.isPaused = false;
963
+ /**
964
+ * Integration will wait until an error occurs before creating and sending a
965
+ * replay.
966
+ */
967
+ this.waitForError = false;
948
968
  /**
949
969
  * Have we attached listeners to the core SDK?
950
970
  * Note we have to track this as there is no way to remove instrumentation handlers.
@@ -989,13 +1009,28 @@ var Replay = /** @class */ (function () {
989
1009
  message: "Tagging event (".concat(event.event_id, ") - ").concat(event.message, " - ").concat((exc === null || exc === void 0 ? void 0 : exc.type) || 'Unknown', ": ").concat((exc === null || exc === void 0 ? void 0 : exc.value) || 'n/a'),
990
1010
  });
991
1011
  // Need to be very careful that this does not cause an infinite loop
992
- if (_this.options.captureOnlyOnError &&
1012
+ if (_this.waitForError &&
993
1013
  event.exception &&
994
- event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because other we could loop indefinitely with trying to capture replay and failing
1014
+ event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because otherwise we could loop indefinitely with trying to capture replay and failing
995
1015
  ) {
996
- // TODO: Do we continue to record after?
997
- // TODO: What happens if another error happens? Do we record in the same session?
998
- setTimeout(function () { return _this.flushImmediate(); });
1016
+ setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
1017
+ return __generator(this, function (_a) {
1018
+ switch (_a.label) {
1019
+ case 0: return [4 /*yield*/, this.flushImmediate()];
1020
+ case 1:
1021
+ _a.sent();
1022
+ if (this.stopRecording) {
1023
+ this.stopRecording();
1024
+ // Reset all "capture on error" configuration before
1025
+ // starting a new recording
1026
+ delete this.recordingOptions.checkoutEveryNms;
1027
+ this.waitForError = false;
1028
+ this.startRecording();
1029
+ }
1030
+ return [2 /*return*/];
1031
+ }
1032
+ });
1033
+ }); });
999
1034
  }
1000
1035
  return event;
1001
1036
  };
@@ -1208,21 +1243,37 @@ var Replay = /** @class */ (function () {
1208
1243
  });
1209
1244
  }); };
1210
1245
  this.recordingOptions = __assign({ maskAllInputs: maskAllInputs, blockClass: blockClass, ignoreClass: ignoreClass, maskTextClass: maskTextClass, blockSelector: blockSelector }, recordingOptions);
1246
+ var usingDeprecatedReplaysSamplingRate = replaysSamplingRate !== undefined;
1247
+ var usingDeprecatedCaptureOnlyOnError = captureOnlyOnError !== undefined;
1211
1248
  this.options = {
1212
1249
  flushMinDelay: flushMinDelay,
1213
1250
  flushMaxDelay: flushMaxDelay,
1214
1251
  stickySession: stickySession,
1215
1252
  initialFlushDelay: initialFlushDelay,
1216
- captureOnlyOnError: captureOnlyOnError,
1217
- replaysSamplingRate: replaysSamplingRate,
1253
+ sessionSampleRate: usingDeprecatedReplaysSamplingRate
1254
+ ? replaysSamplingRate
1255
+ : sessionSampleRate,
1256
+ errorSampleRate: usingDeprecatedCaptureOnlyOnError
1257
+ ? 1.0
1258
+ : errorSampleRate,
1218
1259
  useCompression: useCompression,
1219
1260
  maskAllText: maskAllText,
1220
1261
  blockAllMedia: blockAllMedia,
1221
1262
  };
1222
- // Modify rrweb options to checkoutEveryNthSecond if this is defined, as we don't know when an error occurs, so we want to try to minimize the number of events captured.
1223
- if (this.options.captureOnlyOnError) {
1263
+ // Modify recording options to checkoutEveryNthSecond if this is defined, as we
1264
+ // don't know when an error will occur, so we need to keep a buffer of replay events.
1265
+ if (this.options.errorSampleRate > 0 &&
1266
+ this.options.sessionSampleRate < 1.0) {
1224
1267
  // Checkout every minute, meaning we only get up-to one minute of events before the error happens
1225
1268
  this.recordingOptions.checkoutEveryNms = 60000;
1269
+ this.waitForError = true;
1270
+ }
1271
+ // TODO(deprecated): Maintain backwards compatibility for alpha users
1272
+ if (usingDeprecatedCaptureOnlyOnError) {
1273
+ console.warn('[@sentry/replay]: The `captureOnlyOnError` option is deprecated! Please configure `errorSampleRate` instead.');
1274
+ }
1275
+ if (usingDeprecatedReplaysSamplingRate) {
1276
+ console.warn('[@sentry/replay]: The `replaysSamplingRate` option is deprecated! Please configure `sessionSampleRate` instead.');
1226
1277
  }
1227
1278
  if (this.options.maskAllText) {
1228
1279
  // `maskAllText` is a more user friendly option to configure
@@ -1355,7 +1406,8 @@ var Replay = /** @class */ (function () {
1355
1406
  expiry: expiry,
1356
1407
  stickySession: Boolean(this.options.stickySession),
1357
1408
  currentSession: this.session,
1358
- samplingRate: this.options.replaysSamplingRate,
1409
+ sessionSampleRate: this.options.sessionSampleRate,
1410
+ errorSampleRate: this.options.errorSampleRate,
1359
1411
  }), type = _d.type, session = _d.session;
1360
1412
  // If session was newly created (i.e. was not loaded from storage), then
1361
1413
  // enable flag to create the root replay
@@ -1454,11 +1506,11 @@ var Replay = /** @class */ (function () {
1454
1506
  * processing and hand back control to caller.
1455
1507
  */
1456
1508
  Replay.prototype.addUpdate = function (cb) {
1457
- // We need to always run `cb` (e.g. in the case of captureOnlyOnError == true)
1509
+ // We need to always run `cb` (e.g. in the case of `this.waitForError == true`)
1458
1510
  var cbResult = cb === null || cb === void 0 ? void 0 : cb();
1459
1511
  // If this option is turned on then we will only want to call `flush`
1460
1512
  // explicitly
1461
- if (this.options.captureOnlyOnError) {
1513
+ if (this.waitForError) {
1462
1514
  return;
1463
1515
  }
1464
1516
  // If callback is true, we do not want to continue with flushing -- the
@@ -1689,10 +1741,10 @@ var Replay = /** @class */ (function () {
1689
1741
  return false;
1690
1742
  };
1691
1743
  /**
1692
- * Only flush if `captureOnlyOnError` is false.
1744
+ * Only flush if `this.waitForError` is false.
1693
1745
  */
1694
1746
  Replay.prototype.conditionalFlush = function () {
1695
- if (this.options.captureOnlyOnError) {
1747
+ if (this.waitForError) {
1696
1748
  return;
1697
1749
  }
1698
1750
  this.flushImmediate();
@@ -1791,7 +1843,7 @@ var Replay = /** @class */ (function () {
1791
1843
  Replay.prototype.flushImmediate = function () {
1792
1844
  this.debouncedFlush();
1793
1845
  // `.flush` is provided by lodash.debounce
1794
- this.debouncedFlush.flush();
1846
+ return this.debouncedFlush.flush();
1795
1847
  };
1796
1848
  /**
1797
1849
  * Send replay attachment using `fetch()`
@@ -1815,7 +1867,7 @@ var Replay = /** @class */ (function () {
1815
1867
  timestamp = new Date().getTime();
1816
1868
  sdkInfo = {
1817
1869
  name: 'sentry.javascript.integration.replay',
1818
- version: "0.6.10",
1870
+ version: "0.6.11",
1819
1871
  };
1820
1872
  return [4 /*yield*/, new Promise(function (resolve) {
1821
1873
  var _a;