@sentry/replay 0.2.0-16 → 0.2.0-19

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 (81) hide show
  1. package/dist/{jest.config.d.ts → config/dist/jest.config.d.ts} +0 -0
  2. package/dist/{jest.setup.d.ts → config/dist/jest.setup.d.ts} +2 -2
  3. package/dist/config/dist/src/api/captureReplay.d.ts +2 -0
  4. package/dist/config/dist/src/api/captureReplayUpdate.d.ts +2 -0
  5. package/dist/{src → config/dist/src}/coreHandlers/handleDom.d.ts +0 -0
  6. package/dist/{src → config/dist/src}/coreHandlers/handleFetch.d.ts +0 -0
  7. package/dist/{src/eventBuffer.test.d.ts → config/dist/src/coreHandlers/handleFetch.test.d.ts} +0 -0
  8. package/dist/{src/index.test.d.ts → config/dist/src/coreHandlers/handleScope-unit.test.d.ts} +0 -0
  9. package/dist/config/dist/src/coreHandlers/handleScope.d.ts +3 -0
  10. package/dist/{src/session/createSession.test.d.ts → config/dist/src/coreHandlers/handleScope.test.d.ts} +0 -0
  11. package/dist/{src → config/dist/src}/coreHandlers/handleXhr.d.ts +0 -0
  12. package/dist/{src → config/dist/src}/coreHandlers/index.d.ts +0 -0
  13. package/dist/{src → config/dist/src}/createPerformanceEntry.d.ts +0 -0
  14. package/dist/{src/session/fetchSession.test.d.ts → config/dist/src/createPerformanceEntry.test.d.ts} +0 -0
  15. package/dist/{src → config/dist/src}/eventBuffer.d.ts +1 -6
  16. package/dist/{src/session/getSession.test.d.ts → config/dist/src/eventBuffer.test.d.ts} +0 -0
  17. package/dist/{src → config/dist/src}/flags.d.ts +0 -0
  18. package/dist/{src/session/saveSession.test.d.ts → config/dist/src/index-noSticky.test.d.ts} +0 -0
  19. package/dist/{src → config/dist/src}/index.d.ts +6 -34
  20. package/dist/{src/session/updateSessionActivity.test.d.ts → config/dist/src/index.test.d.ts} +0 -0
  21. package/dist/config/dist/src/session/Session.d.ts +46 -0
  22. package/dist/{src/util/isExpired.test.d.ts → config/dist/src/session/Session.test.d.ts} +0 -0
  23. package/dist/{src → config/dist/src}/session/constants.d.ts +1 -1
  24. package/dist/{src → config/dist/src}/session/createSession.d.ts +2 -2
  25. package/dist/{src/util/isSessionExpired.test.d.ts → config/dist/src/session/createSession.test.d.ts} +0 -0
  26. package/dist/config/dist/src/session/fetchSession.d.ts +2 -0
  27. package/dist/config/dist/src/session/fetchSession.test.d.ts +1 -0
  28. package/dist/{src → config/dist/src}/session/getSession.d.ts +3 -3
  29. package/dist/config/dist/src/session/getSession.test.d.ts +1 -0
  30. package/dist/{src → config/dist/src}/session/index.d.ts +0 -1
  31. package/dist/config/dist/src/session/saveSession.d.ts +2 -0
  32. package/dist/config/dist/src/session/saveSession.test.d.ts +1 -0
  33. package/dist/{src → config/dist/src}/types.d.ts +26 -0
  34. package/dist/{src → config/dist/src}/util/createBreadcrumb.d.ts +0 -0
  35. package/dist/{src → config/dist/src}/util/isExpired.d.ts +0 -0
  36. package/dist/config/dist/src/util/isExpired.test.d.ts +1 -0
  37. package/dist/config/dist/src/util/isIngestHost.d.ts +4 -0
  38. package/dist/config/dist/src/util/isSessionExpired.d.ts +5 -0
  39. package/dist/config/dist/src/util/isSessionExpired.test.d.ts +1 -0
  40. package/dist/{src → config/dist/src}/util/logger.d.ts +1 -0
  41. package/dist/config/dist/test/index.d.ts +3 -0
  42. package/dist/config/dist/test/mocks/mockRrweb.d.ts +15 -0
  43. package/dist/config/dist/test/mocks/mockSdk.d.ts +11 -0
  44. package/dist/dist/coreHandlers/handleDom.d.ts +1 -0
  45. package/dist/dist/coreHandlers/handleFetch.d.ts +2 -0
  46. package/dist/dist/coreHandlers/handleScope.d.ts +3 -0
  47. package/dist/dist/coreHandlers/handleXhr.d.ts +2 -0
  48. package/dist/dist/coreHandlers/index.d.ts +4 -0
  49. package/dist/dist/createPerformanceEntry.d.ts +42 -0
  50. package/dist/dist/eventBuffer.d.ts +31 -0
  51. package/dist/dist/flags.d.ts +2 -0
  52. package/dist/dist/index.d.ts +147 -0
  53. package/dist/dist/session/Session.d.ts +46 -0
  54. package/dist/dist/session/constants.d.ts +5 -0
  55. package/dist/dist/session/createSession.d.ts +14 -0
  56. package/dist/dist/session/fetchSession.d.ts +2 -0
  57. package/dist/dist/session/getSession.d.ts +20 -0
  58. package/dist/dist/session/index.d.ts +1 -0
  59. package/dist/dist/session/saveSession.d.ts +2 -0
  60. package/dist/dist/types.d.ts +57 -0
  61. package/dist/dist/util/createBreadcrumb.d.ts +4 -0
  62. package/dist/dist/util/isExpired.d.ts +5 -0
  63. package/dist/dist/util/isIngestHost.d.ts +4 -0
  64. package/dist/dist/util/isSessionExpired.d.ts +5 -0
  65. package/dist/dist/util/logger.d.ts +12 -0
  66. package/dist/index.es.js +183 -81
  67. package/dist/index.js +183 -81
  68. package/dist/index.js.map +1 -1
  69. package/package.json +12 -9
  70. package/dist/rollup.config.d.ts +0 -3
  71. package/dist/src/coreHandlers/handleScope.d.ts +0 -2
  72. package/dist/src/createMemoryEntry.d.ts +0 -19
  73. package/dist/src/session/fetchSession.d.ts +0 -2
  74. package/dist/src/session/saveSession.d.ts +0 -2
  75. package/dist/src/session/types.d.ts +0 -6
  76. package/dist/src/session/updateSessionActivity.d.ts +0 -3
  77. package/dist/src/util/isSessionExpired.d.ts +0 -5
  78. package/dist/test/index.d.ts +0 -1
  79. package/dist/worker-9d2d4d71.js +0 -7
  80. package/dist/worker-9d2d4d71.js.map +0 -1
  81. package/dist/worker-c801dc28.js +0 -4
@@ -0,0 +1,46 @@
1
+ interface SessionObject {
2
+ id: string;
3
+ /**
4
+ * Start time of current session
5
+ */
6
+ started: number;
7
+ /**
8
+ * Last known activity of the session
9
+ */
10
+ lastActivity: number;
11
+ /**
12
+ * Sequence ID specific to replay updates
13
+ */
14
+ sequenceId: number;
15
+ }
16
+ interface SessionOptions {
17
+ stickySession?: boolean;
18
+ }
19
+ export declare class Session {
20
+ /**
21
+ * Session ID
22
+ */
23
+ private _id;
24
+ /**
25
+ * Start time of current session
26
+ */
27
+ private _started;
28
+ /**
29
+ * Last known activity of the session
30
+ */
31
+ private _lastActivity;
32
+ /**
33
+ * Sequence ID specific to replay updates
34
+ */
35
+ private _sequenceId;
36
+ private options;
37
+ constructor(session?: Partial<SessionObject>, { stickySession }?: SessionOptions);
38
+ get id(): string;
39
+ get started(): number;
40
+ get lastActivity(): number;
41
+ set lastActivity(newDate: number);
42
+ get sequenceId(): number;
43
+ set sequenceId(id: number);
44
+ toJSON(): SessionObject;
45
+ }
46
+ export {};
@@ -0,0 +1,5 @@
1
+ export declare const REPLAY_SESSION_KEY = "sentryReplaySession";
2
+ export declare const ROOT_REPLAY_NAME = "sentry-replay";
3
+ export declare const REPLAY_EVENT_NAME = "sentry-replay-event";
4
+ export declare const SESSION_IDLE_DURATION = 900000;
5
+ export declare const VISIBILITY_CHANGE_TIMEOUT = 900000;
@@ -0,0 +1,14 @@
1
+ import { Session } from './Session';
2
+ interface CreateSessionParams {
3
+ /**
4
+ * Should save to sessionStorage?
5
+ */
6
+ stickySession: boolean;
7
+ }
8
+ /**
9
+ * Create a new session, which in its current implementation is a Sentry event
10
+ * that all replays will be saved to as attachments. Currently, we only expect
11
+ * one of these Sentry events per "replay session".
12
+ */
13
+ export declare function createSession({ stickySession, }: CreateSessionParams): Session;
14
+ export {};
@@ -0,0 +1,2 @@
1
+ import { Session } from './Session';
2
+ export declare function fetchSession(): Session | null;
@@ -0,0 +1,20 @@
1
+ import { Session } from './Session';
2
+ interface GetSessionParams {
3
+ /**
4
+ * The length of time (in ms) which we will consider the session to be expired.
5
+ */
6
+ expiry: number;
7
+ /**
8
+ * Should save session to sessionStorage?
9
+ */
10
+ stickySession: boolean;
11
+ /**
12
+ * The current session (e.g. if stickySession is off)
13
+ */
14
+ currentSession?: Session;
15
+ }
16
+ /**
17
+ * Get or create a session
18
+ */
19
+ export declare function getSession({ expiry, currentSession, stickySession, }: GetSessionParams): Session;
20
+ export {};
@@ -0,0 +1 @@
1
+ export * from './createSession';
@@ -0,0 +1,2 @@
1
+ import { Session } from './Session';
2
+ export declare function saveSession(session: Session): void;
@@ -0,0 +1,57 @@
1
+ import type { eventWithTime } from 'rrweb/typings/types';
2
+ import { record } from 'rrweb';
3
+ export declare type RRWebEvent = eventWithTime;
4
+ export declare type RRWebOptions = Parameters<typeof record>[0];
5
+ export interface ReplaySpan {
6
+ description: string;
7
+ op: string;
8
+ startTimestamp: number;
9
+ endTimestamp: number;
10
+ data?: Record<string, unknown>;
11
+ }
12
+ export interface ReplayRequest {
13
+ endpoint: string;
14
+ events: Uint8Array | string;
15
+ }
16
+ export declare type InstrumentationType = 'scope' | 'dom' | 'fetch' | 'xhr';
17
+ /**
18
+ * The request payload to worker
19
+ */
20
+ export interface WorkerRequest {
21
+ method: string;
22
+ args: any[];
23
+ }
24
+ /**
25
+ * The response from the worker
26
+ */
27
+ export interface WorkerResponse {
28
+ method: string;
29
+ success: boolean;
30
+ response: string | Uint8Array;
31
+ }
32
+ export interface SentryReplayPluginOptions {
33
+ /**
34
+ * The amount of time to wait before sending a replay
35
+ */
36
+ uploadMinDelay?: number;
37
+ /**
38
+ * The max amount of time to wait before sending a replay
39
+ */
40
+ uploadMaxDelay?: number;
41
+ /**
42
+ * If false, will create a new session per pageload
43
+ */
44
+ stickySession?: boolean;
45
+ /**
46
+ * Attempt to use compression when web workers are available
47
+ *
48
+ * (default is true)
49
+ */
50
+ useCompression?: boolean;
51
+ }
52
+ export interface SentryReplayConfiguration extends SentryReplayPluginOptions {
53
+ /**
54
+ * Options for `rrweb.recordsetup
55
+ */
56
+ rrwebConfig?: RRWebOptions;
57
+ }
@@ -0,0 +1,4 @@
1
+ import type { Breadcrumb } from '@sentry/types';
2
+ declare type RequiredProperties = 'category' | 'message';
3
+ export default function createBreadcrumb(breadcrumb: Pick<Breadcrumb, RequiredProperties> & Partial<Omit<Breadcrumb, RequiredProperties>>): Breadcrumb;
4
+ export {};
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Given an initial timestamp and an expiry duration, checks to see if current
3
+ * time should be considered as expired.
4
+ */
5
+ export declare function isExpired(initialTime: number, expiry: number, targetTime?: number): boolean;
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Checks is `targetHost` is a Sentry ingestion host
3
+ */
4
+ export declare function isIngestHost(targetHost: string): boolean;
@@ -0,0 +1,5 @@
1
+ import { Session } from '@/session/Session';
2
+ /**
3
+ * Checks to see if session is expired
4
+ */
5
+ export declare function isSessionExpired(session: Session, expiry: number, targetTime?: number): boolean;
@@ -0,0 +1,12 @@
1
+ declare const logger: {
2
+ error: (...args: any[]) => any;
3
+ warn: (...args: any[]) => any;
4
+ log: (...args: any[]) => any;
5
+ disable(): void;
6
+ enable(): void;
7
+ debug: (...args: unknown[]) => void;
8
+ info: (...args: unknown[]) => void;
9
+ assert: (...args: unknown[]) => void;
10
+ trace: (...args: unknown[]) => void;
11
+ };
12
+ export { logger };
package/dist/index.es.js CHANGED
@@ -89,6 +89,14 @@ function __spreadArray(to, from, pack) {
89
89
  return to.concat(ar || Array.prototype.slice.call(from));
90
90
  }
91
91
 
92
+ /**
93
+ * Checks is `targetHost` is a Sentry ingestion host
94
+ */
95
+ function isIngestHost(targetHost) {
96
+ var _a = getCurrentHub().getClient().getDsn(), protocol = _a.protocol, host = _a.host;
97
+ return targetHost.startsWith("".concat(protocol, "://").concat(host));
98
+ }
99
+
92
100
  var _a;
93
101
  // Map entryType -> function to normalize data for event
94
102
  var ENTRY_TYPES = (_a = {
@@ -134,11 +142,9 @@ function createNavigationEntry(entry) {
134
142
  };
135
143
  }
136
144
  function createResourceEntry(entry) {
137
- var _a, _b;
138
145
  var entryType = entry.entryType, initiatorType = entry.initiatorType, name = entry.name, responseEnd = entry.responseEnd, startTime = entry.startTime, transferSize = entry.transferSize;
139
146
  // Do not capture fetches to Sentry ingestion endpoint
140
- var _c = ((_b = (_a = getCurrentHub()) === null || _a === void 0 ? void 0 : _a.getClient()) === null || _b === void 0 ? void 0 : _b.getDsn()) || {}, host = _c.host, protocol = _c.protocol;
141
- if (name.startsWith("".concat(protocol, "://").concat(host))) {
147
+ if (isIngestHost(name)) {
142
148
  return null;
143
149
  }
144
150
  return {
@@ -330,10 +336,10 @@ var EventBufferCompressionWorker = /** @class */ (function () {
330
336
  var REPLAY_SESSION_KEY = 'sentryReplaySession';
331
337
  var ROOT_REPLAY_NAME = 'sentry-replay';
332
338
  var REPLAY_EVENT_NAME = 'sentry-replay-event';
333
- // Grace period to keep a session when a user changes tabs or hides window
334
- var VISIBILITY_CHANGE_TIMEOUT = 60000; // 1 minute
335
339
  // The idle limit for a session
336
340
  var SESSION_IDLE_DURATION = 900000; // 15 minutes
341
+ // Grace period to keep a session when a user changes tabs or hides window
342
+ var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
337
343
 
338
344
  /**
339
345
  * Given an initial timestamp and an expiry duration, checks to see if current
@@ -373,6 +379,71 @@ function saveSession(session) {
373
379
  }
374
380
  }
375
381
 
382
+ var Session = /** @class */ (function () {
383
+ function Session(session, _a) {
384
+ if (session === void 0) { session = {}; }
385
+ var _b = _a === void 0 ? {} : _a, _c = _b.stickySession, stickySession = _c === void 0 ? false : _c;
386
+ var _d, _e, _f;
387
+ var now = new Date().getTime();
388
+ this._id = session.id || uuid4();
389
+ this._started = (_d = session.started) !== null && _d !== void 0 ? _d : now;
390
+ this._lastActivity = (_e = session.lastActivity) !== null && _e !== void 0 ? _e : now;
391
+ this._sequenceId = (_f = session.sequenceId) !== null && _f !== void 0 ? _f : 0;
392
+ this.options = {
393
+ stickySession: stickySession,
394
+ };
395
+ }
396
+ Object.defineProperty(Session.prototype, "id", {
397
+ get: function () {
398
+ return this._id;
399
+ },
400
+ enumerable: false,
401
+ configurable: true
402
+ });
403
+ Object.defineProperty(Session.prototype, "started", {
404
+ get: function () {
405
+ return this._started;
406
+ },
407
+ enumerable: false,
408
+ configurable: true
409
+ });
410
+ Object.defineProperty(Session.prototype, "lastActivity", {
411
+ get: function () {
412
+ return this._lastActivity;
413
+ },
414
+ set: function (newDate) {
415
+ this._lastActivity = newDate;
416
+ if (this.options.stickySession) {
417
+ saveSession(this);
418
+ }
419
+ },
420
+ enumerable: false,
421
+ configurable: true
422
+ });
423
+ Object.defineProperty(Session.prototype, "sequenceId", {
424
+ get: function () {
425
+ return this._sequenceId;
426
+ },
427
+ set: function (id) {
428
+ this._sequenceId = id;
429
+ if (this.options.stickySession) {
430
+ saveSession(this);
431
+ }
432
+ },
433
+ enumerable: false,
434
+ configurable: true
435
+ });
436
+ Session.prototype.toJSON = function () {
437
+ return {
438
+ id: this.id,
439
+ started: this.started,
440
+ lastActivity: this.lastActivity,
441
+ sequenceId: this._sequenceId,
442
+ };
443
+ };
444
+ return Session;
445
+ }());
446
+
376
447
  /**
377
448
  * Create a new session, which in its current implementation is a Sentry event
378
449
  * that all replays will be saved to as attachments. Currently, we only expect
@@ -380,14 +451,8 @@ function saveSession(session) {
380
451
  */
381
452
  function createSession(_a) {
382
453
  var _b = _a.stickySession, stickySession = _b === void 0 ? false : _b;
383
- var currentDate = new Date().getTime();
384
454
  var hub = getCurrentHub();
385
- var session = {
386
- id: uuid4(),
387
- started: currentDate,
388
- lastActivity: currentDate,
389
- sequenceId: 0,
390
- };
455
+ var session = new Session(undefined, { stickySession: stickySession });
391
456
  hub.captureEvent({
392
457
  message: ROOT_REPLAY_NAME,
393
458
  tags: { sequenceId: session.sequenceId },
@@ -405,7 +470,10 @@ function fetchSession() {
405
470
  return null;
406
471
  }
407
472
  try {
408
- return JSON.parse(window.sessionStorage.getItem(REPLAY_SESSION_KEY));
473
+ return new Session(JSON.parse(window.sessionStorage.getItem(REPLAY_SESSION_KEY)),
474
+ // We are assuming that if there is a saved item, then the session is sticky,
475
+ // however this could break down if we used a different storage mechanism (e.g. localstorage)
476
+ { stickySession: true });
409
477
  }
410
478
  catch (_a) {
411
479
  return null;
@@ -435,24 +503,6 @@ function getSession(_a) {
435
503
  return newSession;
436
504
  }
437
505
 
438
- function updateSessionActivity(_a) {
439
- var stickySession = _a.stickySession;
440
- // Nothing to do if there are no sticky sessions
441
- if (!stickySession) {
442
- return;
443
- }
444
- var existingSession = fetchSession();
445
- // If user manually deleted from session storage, create a new session
446
- if (!existingSession) {
447
- // TBD: There was an issue here where sessions weren't saving and this
448
- // caused lots of transactions to be created
449
- return createSession({ stickySession: stickySession });
450
- }
451
- var newSession = __assign(__assign({}, existingSession), { lastActivity: new Date().getTime() });
452
- saveSession(newSession);
453
- return newSession;
454
- }
455
-
456
506
  function createBreadcrumb(breadcrumb) {
457
507
  return __assign({ timestamp: new Date().getTime() / 1000, type: 'default' }, breadcrumb);
458
508
  }
@@ -522,9 +572,10 @@ function handleXhr(handlerData) {
522
572
  if (!handlerData.endTimestamp) {
523
573
  return null;
524
574
  }
575
+ var _a = handlerData.args, op = _a[0], description = _a[1];
525
576
  return {
526
- description: handlerData.args[1],
527
- op: handlerData.args[0],
577
+ description: description,
578
+ op: op,
528
579
  startTimestamp: handlerData.xhr.__sentry_xhr__.startTimestamp / 1000 ||
529
580
  handlerData.endTimestamp / 1000.0,
530
581
  endTimestamp: handlerData.endTimestamp / 1000.0,
@@ -568,58 +619,51 @@ var SentryReplay = /** @class */ (function () {
568
619
  this.retryCount = 0;
569
620
  this.retryInterval = BASE_RETRY_INTERVAL;
570
621
  /**
571
- * Handle when visibility of the page changes. (e.g. new tab is opened)
622
+ * If current browser window in an active state
623
+ */
624
+ this.isActive = true;
625
+ /**
626
+ * Handle when visibility of the page content changes. Opening a new tab will
627
+ * cause the state to change to hidden because of content of current page will
628
+ * be hidden. Likewise, moving a different window to cover the contents of the
629
+ * page will also trigger a change to a hidden state.
572
630
  */
573
631
  this.handleVisibilityChange = function () {
574
- var isExpired = isSessionExpired(_this.session, VISIBILITY_CHANGE_TIMEOUT);
575
- if (isExpired) {
576
- if (document.visibilityState === 'visible') {
577
- // If the user has come back to the page within VISIBILITY_CHANGE_TIMEOUT
578
- // ms, we will re-use the existing session, otherwise create a new
579
- // session
580
- logger.log('Document has become active, but session has expired');
581
- _this.loadSession({ expiry: VISIBILITY_CHANGE_TIMEOUT });
582
- _this.triggerFullSnapshot();
583
- }
584
- // We definitely want to return if visibilityState is "visible", and I
585
- // think we also want to do the same when "hidden", as there shouldn't be
586
- // any action to take if user has gone idle for a long period and then
587
- // comes back to hide the tab. We don't trigger a full snapshot because
588
- // we don't want to start a new session as they immediately have hidden
589
- // the tab.
590
- return;
632
+ var breadcrumb = createBreadcrumb({
633
+ category: 'ui.other',
634
+ data: {
635
+ label: "Page is ".concat(document.visibilityState),
636
+ },
637
+ });
638
+ if (document.visibilityState === 'visible') {
639
+ _this.doChangeToForegroundTasks(breadcrumb);
591
640
  }
592
- // Otherwise if session is not expired...
593
- // Update with current timestamp as the last session activity
594
- // Only updating session on visibility change to be conservative about
595
- // writing to session storage. This could be changed in the future.
596
- _this.updateSession(updateSessionActivity({
597
- stickySession: _this.options.stickySession,
598
- }));
599
- // Send replay when the page/tab becomes hidden. There is no reason to send
600
- // replay if it becomes visible, since no actions we care about were done
601
- // while it was hidden
602
- if (document.visibilityState !== 'visible') {
603
- _this.flushUpdate();
641
+ else {
642
+ _this.doChangeToBackgroundTasks(breadcrumb);
604
643
  }
605
644
  };
606
- this.handleWindowUnload = function () {
645
+ /**
646
+ * Handle when page is blurred
647
+ */
648
+ this.handleWindowBlur = function () {
607
649
  var breadcrumb = createBreadcrumb({
608
- category: 'ui.exit',
609
- message: '',
650
+ category: 'ui.blur',
610
651
  });
611
- _this.addUpdate(function () {
612
- _this.eventBuffer.addEvent({
613
- type: EventType.Custom,
614
- // TODO: We were converting from ms to seconds for breadcrumbs, spans,
615
- // but maybe we should just keep them as milliseconds
616
- timestamp: breadcrumb.timestamp,
617
- data: {
618
- tag: 'breadcrumb',
619
- payload: breadcrumb,
620
- },
621
- });
652
+ _this.doChangeToBackgroundTasks(breadcrumb);
653
+ };
654
+ /**
655
+ * Handle when page is focused
656
+ */
657
+ this.handleWindowFocus = function () {
658
+ var breadcrumb = createBreadcrumb({
659
+ category: 'ui.focus',
622
660
  });
661
+ _this.doChangeToForegroundTasks(breadcrumb);
662
+ };
663
+ this.handleWindowUnload = function () {
664
+ _this.createCustomBreadcrumb(createBreadcrumb({
665
+ category: 'ui.exit',
666
+ }));
623
667
  };
624
668
  this.handleCoreListener = function (type) { return function (handlerData) {
625
669
  var handlerMap = {
@@ -784,12 +828,11 @@ var SentryReplay = /** @class */ (function () {
784
828
  currentSession: this.session,
785
829
  });
786
830
  };
787
- SentryReplay.prototype.updateSession = function (session) {
788
- this.session = __assign(__assign({}, this.session), session);
789
- };
790
831
  SentryReplay.prototype.addListeners = function () {
791
832
  var _this = this;
792
833
  document.addEventListener('visibilitychange', this.handleVisibilityChange);
834
+ window.addEventListener('blur', this.handleWindowBlur);
835
+ window.addEventListener('focus', this.handleWindowFocus);
793
836
  window.addEventListener('beforeunload', this.handleWindowUnload);
794
837
  // Listeners from core SDK //
795
838
  var scope = Sentry.getCurrentHub().getScope();
@@ -826,6 +869,48 @@ var SentryReplay = /** @class */ (function () {
826
869
  this.performanceObserver = null;
827
870
  }
828
871
  };
872
+ /**
873
+ * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)
874
+ */
875
+ SentryReplay.prototype.doChangeToBackgroundTasks = function (breadcrumb) {
876
+ var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
877
+ // We check current state to make sure that we do nothing if the page is already inactive
878
+ if (!this.isActive) {
879
+ return;
880
+ }
881
+ this.createCustomBreadcrumb(__assign(__assign({}, breadcrumb), {
882
+ // if somehow the page went hidden while session is expired, attach to previous session
883
+ timestamp: isExpired
884
+ ? this.session.lastActivity / 1000
885
+ : breadcrumb.timestamp }));
886
+ this.isActive = false;
887
+ // Send replay when the page/tab becomes hidden. There is no reason to send
888
+ // replay if it becomes visible, since no actions we care about were done
889
+ // while it was hidden
890
+ this.flushUpdate();
891
+ };
892
+ /**
893
+ * Tasks to run when we consider a page to be visible (via focus and/or visibility)
894
+ */
895
+ SentryReplay.prototype.doChangeToForegroundTasks = function (breadcrumb) {
896
+ var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
897
+ this.isActive = true;
898
+ this.createCustomBreadcrumb(__assign(__assign({}, breadcrumb), { timestamp: isExpired ? new Date().getTime() / 1000 : breadcrumb.timestamp }));
899
+ if (isExpired) {
900
+ // If the user has come back to the page within VISIBILITY_CHANGE_TIMEOUT
901
+ // ms, we will re-use the existing session, otherwise create a new
902
+ // session
903
+ logger.log('Document has become active, but session has expired');
904
+ this.loadSession({ expiry: VISIBILITY_CHANGE_TIMEOUT });
905
+ this.triggerFullSnapshot();
906
+ return;
907
+ }
908
+ // Otherwise if session is not expired...
909
+ // Update with current timestamp as the last session activity
910
+ // Only updating session on visibility change to be conservative about
911
+ // writing to session storage. This could be changed in the future.
912
+ this.updateLastActivity();
913
+ };
829
914
  /**
830
915
  * Trigger rrweb to take a full snapshot which will cause this plugin to
831
916
  * create a new Replay event.
@@ -834,6 +919,23 @@ var SentryReplay = /** @class */ (function () {
834
919
  logger.log('Taking full rrweb snapshot');
835
920
  record.takeFullSnapshot(true);
836
921
  };
922
+ SentryReplay.prototype.updateLastActivity = function (lastActivity) {
923
+ if (lastActivity === void 0) { lastActivity = new Date().getTime(); }
924
+ this.session.lastActivity = lastActivity;
925
+ };
926
+ SentryReplay.prototype.createCustomBreadcrumb = function (breadcrumb) {
927
+ var _this = this;
928
+ this.addUpdate(function () {
929
+ _this.eventBuffer.addEvent({
930
+ type: EventType.Custom,
931
+ timestamp: breadcrumb.timestamp,
932
+ data: {
933
+ tag: 'breadcrumb',
934
+ payload: breadcrumb,
935
+ },
936
+ });
937
+ });
938
+ };
837
939
  /**
838
940
  * Create a span for each performance entry. The parent transaction is `this.replayEvent`.
839
941
  */
@@ -926,7 +1028,7 @@ var SentryReplay = /** @class */ (function () {
926
1028
  this.sendReplay(this.session.id, recordingData);
927
1029
  this.initialEventTimestampSinceFlush = null;
928
1030
  // TBD: Alternatively we could update this after every rrweb event
929
- this.session.lastActivity = lastActivity || new Date().getTime();
1031
+ this.updateLastActivity(lastActivity);
930
1032
  return [2 /*return*/];
931
1033
  }
932
1034
  });