@sentry/browser 6.16.1 → 6.17.2

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 (111) hide show
  1. package/build/bundle.es6.js +1311 -1428
  2. package/build/bundle.es6.js.map +1 -1
  3. package/build/bundle.es6.min.js +2 -2
  4. package/build/bundle.es6.min.js.map +1 -1
  5. package/build/bundle.js +1350 -1483
  6. package/build/bundle.js.map +1 -1
  7. package/build/bundle.min.js +2 -2
  8. package/build/bundle.min.js.map +1 -1
  9. package/dist/eventbuilder.d.ts +2 -2
  10. package/dist/eventbuilder.d.ts.map +1 -1
  11. package/dist/eventbuilder.js +7 -7
  12. package/dist/eventbuilder.js.map +1 -1
  13. package/dist/exports.d.ts +1 -1
  14. package/dist/exports.d.ts.map +1 -1
  15. package/dist/exports.js +0 -1
  16. package/dist/exports.js.map +1 -1
  17. package/dist/helpers.d.ts.map +1 -1
  18. package/dist/helpers.js +26 -37
  19. package/dist/helpers.js.map +1 -1
  20. package/dist/integrations/breadcrumbs.d.ts +0 -20
  21. package/dist/integrations/breadcrumbs.d.ts.map +1 -1
  22. package/dist/integrations/breadcrumbs.js +132 -173
  23. package/dist/integrations/breadcrumbs.js.map +1 -1
  24. package/dist/integrations/dedupe.d.ts +0 -14
  25. package/dist/integrations/dedupe.d.ts.map +1 -1
  26. package/dist/integrations/dedupe.js +126 -126
  27. package/dist/integrations/dedupe.js.map +1 -1
  28. package/dist/integrations/globalhandlers.d.ts +7 -25
  29. package/dist/integrations/globalhandlers.d.ts.map +1 -1
  30. package/dist/integrations/globalhandlers.js +176 -168
  31. package/dist/integrations/globalhandlers.js.map +1 -1
  32. package/dist/integrations/linkederrors.d.ts +15 -13
  33. package/dist/integrations/linkederrors.d.ts.map +1 -1
  34. package/dist/integrations/linkederrors.js +26 -28
  35. package/dist/integrations/linkederrors.js.map +1 -1
  36. package/dist/integrations/trycatch.d.ts +0 -8
  37. package/dist/integrations/trycatch.d.ts.map +1 -1
  38. package/dist/integrations/trycatch.js +154 -153
  39. package/dist/integrations/trycatch.js.map +1 -1
  40. package/dist/integrations/useragent.js +2 -3
  41. package/dist/integrations/useragent.js.map +1 -1
  42. package/dist/sdk.d.ts.map +1 -1
  43. package/dist/sdk.js +23 -19
  44. package/dist/sdk.js.map +1 -1
  45. package/dist/transports/base.d.ts +9 -4
  46. package/dist/transports/base.d.ts.map +1 -1
  47. package/dist/transports/base.js +23 -19
  48. package/dist/transports/base.js.map +1 -1
  49. package/dist/transports/fetch.d.ts +2 -10
  50. package/dist/transports/fetch.d.ts.map +1 -1
  51. package/dist/transports/fetch.js +6 -20
  52. package/dist/transports/fetch.js.map +1 -1
  53. package/dist/transports/utils.d.ts.map +1 -1
  54. package/dist/transports/utils.js +7 -5
  55. package/dist/transports/utils.js.map +1 -1
  56. package/dist/transports/xhr.d.ts +2 -10
  57. package/dist/transports/xhr.d.ts.map +1 -1
  58. package/dist/transports/xhr.js +3 -17
  59. package/dist/transports/xhr.js.map +1 -1
  60. package/esm/eventbuilder.d.ts +2 -2
  61. package/esm/eventbuilder.d.ts.map +1 -1
  62. package/esm/eventbuilder.js +8 -8
  63. package/esm/eventbuilder.js.map +1 -1
  64. package/esm/exports.d.ts +1 -1
  65. package/esm/exports.d.ts.map +1 -1
  66. package/esm/exports.js +1 -1
  67. package/esm/exports.js.map +1 -1
  68. package/esm/helpers.d.ts.map +1 -1
  69. package/esm/helpers.js +28 -39
  70. package/esm/helpers.js.map +1 -1
  71. package/esm/integrations/breadcrumbs.d.ts +0 -20
  72. package/esm/integrations/breadcrumbs.d.ts.map +1 -1
  73. package/esm/integrations/breadcrumbs.js +134 -175
  74. package/esm/integrations/breadcrumbs.js.map +1 -1
  75. package/esm/integrations/dedupe.d.ts +0 -14
  76. package/esm/integrations/dedupe.d.ts.map +1 -1
  77. package/esm/integrations/dedupe.js +126 -126
  78. package/esm/integrations/dedupe.js.map +1 -1
  79. package/esm/integrations/globalhandlers.d.ts +7 -25
  80. package/esm/integrations/globalhandlers.d.ts.map +1 -1
  81. package/esm/integrations/globalhandlers.js +178 -170
  82. package/esm/integrations/globalhandlers.js.map +1 -1
  83. package/esm/integrations/linkederrors.d.ts +15 -13
  84. package/esm/integrations/linkederrors.d.ts.map +1 -1
  85. package/esm/integrations/linkederrors.js +24 -28
  86. package/esm/integrations/linkederrors.js.map +1 -1
  87. package/esm/integrations/trycatch.d.ts +0 -8
  88. package/esm/integrations/trycatch.d.ts.map +1 -1
  89. package/esm/integrations/trycatch.js +155 -154
  90. package/esm/integrations/trycatch.js.map +1 -1
  91. package/esm/integrations/useragent.js +2 -3
  92. package/esm/integrations/useragent.js.map +1 -1
  93. package/esm/sdk.d.ts.map +1 -1
  94. package/esm/sdk.js +24 -20
  95. package/esm/sdk.js.map +1 -1
  96. package/esm/transports/base.d.ts +9 -4
  97. package/esm/transports/base.d.ts.map +1 -1
  98. package/esm/transports/base.js +25 -21
  99. package/esm/transports/base.js.map +1 -1
  100. package/esm/transports/fetch.d.ts +2 -10
  101. package/esm/transports/fetch.d.ts.map +1 -1
  102. package/esm/transports/fetch.js +6 -20
  103. package/esm/transports/fetch.js.map +1 -1
  104. package/esm/transports/utils.d.ts.map +1 -1
  105. package/esm/transports/utils.js +8 -6
  106. package/esm/transports/utils.js.map +1 -1
  107. package/esm/transports/xhr.d.ts +2 -10
  108. package/esm/transports/xhr.d.ts.map +1 -1
  109. package/esm/transports/xhr.js +3 -17
  110. package/esm/transports/xhr.js.map +1 -1
  111. package/package.json +4 -5
package/build/bundle.js CHANGED
@@ -1,4 +1,4 @@
1
- /*! @sentry/browser 6.16.1 (6919d17) | https://github.com/getsentry/sentry-javascript */
1
+ /*! @sentry/browser 6.17.2 (37b1213) | https://github.com/getsentry/sentry-javascript */
2
2
  var Sentry = (function (exports) {
3
3
  /*! *****************************************************************************
4
4
  Copyright (c) Microsoft Corporation. All rights reserved.
@@ -40,16 +40,6 @@ var Sentry = (function (exports) {
40
40
  return __assign.apply(this, arguments);
41
41
  };
42
42
 
43
- function __rest(s, e) {
44
- var t = {};
45
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
46
- t[p] = s[p];
47
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
48
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
49
- t[p[i]] = s[p[i]];
50
- return t;
51
- }
52
-
53
43
  function __values(o) {
54
44
  var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
55
45
  if (m) return m.call(o);
@@ -84,44 +74,9 @@ var Sentry = (function (exports) {
84
74
  return ar;
85
75
  }
86
76
 
87
- /** Console logging verbosity for the SDK. */
88
- var LogLevel;
89
- (function (LogLevel) {
90
- /** No logs will be generated. */
91
- LogLevel[LogLevel["None"] = 0] = "None";
92
- /** Only SDK internal errors will be logged. */
93
- LogLevel[LogLevel["Error"] = 1] = "Error";
94
- /** Information useful for debugging the SDK will be logged. */
95
- LogLevel[LogLevel["Debug"] = 2] = "Debug";
96
- /** All SDK actions will be logged. */
97
- LogLevel[LogLevel["Verbose"] = 3] = "Verbose";
98
- })(LogLevel || (LogLevel = {}));
99
-
100
77
  /**
101
- * Session Status
78
+ * TODO(v7): Remove this enum and replace with SeverityLevel
102
79
  */
103
- var SessionStatus;
104
- (function (SessionStatus) {
105
- /** JSDoc */
106
- SessionStatus["Ok"] = "ok";
107
- /** JSDoc */
108
- SessionStatus["Exited"] = "exited";
109
- /** JSDoc */
110
- SessionStatus["Crashed"] = "crashed";
111
- /** JSDoc */
112
- SessionStatus["Abnormal"] = "abnormal";
113
- })(SessionStatus || (SessionStatus = {}));
114
- var RequestSessionStatus;
115
- (function (RequestSessionStatus) {
116
- /** JSDoc */
117
- RequestSessionStatus["Ok"] = "ok";
118
- /** JSDoc */
119
- RequestSessionStatus["Errored"] = "errored";
120
- /** JSDoc */
121
- RequestSessionStatus["Crashed"] = "crashed";
122
- })(RequestSessionStatus || (RequestSessionStatus = {}));
123
-
124
- /** JSDoc */
125
80
  (function (Severity) {
126
81
  /** JSDoc */
127
82
  Severity["Fatal"] = "fatal";
@@ -138,95 +93,7 @@ var Sentry = (function (exports) {
138
93
  /** JSDoc */
139
94
  Severity["Critical"] = "critical";
140
95
  })(exports.Severity || (exports.Severity = {}));
141
- // eslint-disable-next-line @typescript-eslint/no-namespace, import/export
142
- (function (Severity) {
143
- /**
144
- * Converts a string-based level into a {@link Severity}.
145
- *
146
- * @param level string representation of Severity
147
- * @returns Severity
148
- */
149
- function fromString(level) {
150
- switch (level) {
151
- case 'debug':
152
- return Severity.Debug;
153
- case 'info':
154
- return Severity.Info;
155
- case 'warn':
156
- case 'warning':
157
- return Severity.Warning;
158
- case 'error':
159
- return Severity.Error;
160
- case 'fatal':
161
- return Severity.Fatal;
162
- case 'critical':
163
- return Severity.Critical;
164
- case 'log':
165
- default:
166
- return Severity.Log;
167
- }
168
- }
169
- Severity.fromString = fromString;
170
- })(exports.Severity || (exports.Severity = {}));
171
-
172
- /** The status of an event. */
173
- (function (Status) {
174
- /** The status could not be determined. */
175
- Status["Unknown"] = "unknown";
176
- /** The event was skipped due to configuration or callbacks. */
177
- Status["Skipped"] = "skipped";
178
- /** The event was sent to Sentry successfully. */
179
- Status["Success"] = "success";
180
- /** The client is currently rate limited and will try again later. */
181
- Status["RateLimit"] = "rate_limit";
182
- /** The event could not be processed. */
183
- Status["Invalid"] = "invalid";
184
- /** A server-side error occurred during submission. */
185
- Status["Failed"] = "failed";
186
- })(exports.Status || (exports.Status = {}));
187
- // eslint-disable-next-line @typescript-eslint/no-namespace, import/export
188
- (function (Status) {
189
- /**
190
- * Converts a HTTP status code into a {@link Status}.
191
- *
192
- * @param code The HTTP response status code.
193
- * @returns The send status or {@link Status.Unknown}.
194
- */
195
- function fromHttpCode(code) {
196
- if (code >= 200 && code < 300) {
197
- return Status.Success;
198
- }
199
- if (code === 429) {
200
- return Status.RateLimit;
201
- }
202
- if (code >= 400 && code < 500) {
203
- return Status.Invalid;
204
- }
205
- if (code >= 500) {
206
- return Status.Failed;
207
- }
208
- return Status.Unknown;
209
- }
210
- Status.fromHttpCode = fromHttpCode;
211
- })(exports.Status || (exports.Status = {}));
212
-
213
- var TransactionSamplingMethod;
214
- (function (TransactionSamplingMethod) {
215
- TransactionSamplingMethod["Explicit"] = "explicitly_set";
216
- TransactionSamplingMethod["Sampler"] = "client_sampler";
217
- TransactionSamplingMethod["Rate"] = "client_rate";
218
- TransactionSamplingMethod["Inheritance"] = "inheritance";
219
- })(TransactionSamplingMethod || (TransactionSamplingMethod = {}));
220
-
221
- var Outcome;
222
- (function (Outcome) {
223
- Outcome["BeforeSend"] = "before_send";
224
- Outcome["EventProcessor"] = "event_processor";
225
- Outcome["NetworkError"] = "network_error";
226
- Outcome["QueueOverflow"] = "queue_overflow";
227
- Outcome["RateLimitBackoff"] = "ratelimit_backoff";
228
- Outcome["SampleRate"] = "sample_rate";
229
- })(Outcome || (Outcome = {}));
96
+ var SeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug', 'critical'];
230
97
 
231
98
  /**
232
99
  * Consumes the promise and logs the error when it rejects.
@@ -241,6 +108,33 @@ var Sentry = (function (exports) {
241
108
  });
242
109
  }
243
110
 
111
+ /**
112
+ * This module mostly exists for optimizations in the build process
113
+ * through rollup and terser. We define some global constants which
114
+ * are normally undefined. However terser overrides these with global
115
+ * definitions which can be evaluated by the static analyzer when
116
+ * creating a bundle.
117
+ *
118
+ * In turn the `isDebugBuild` and `isBrowserBundle` functions are pure
119
+ * and can help us remove unused code from the bundles.
120
+ */
121
+ /**
122
+ * Figures out if we're building with debug functionality.
123
+ *
124
+ * @returns true if this is a debug build
125
+ */
126
+ function isDebugBuild() {
127
+ return typeof __SENTRY_NO_DEBUG__ !== 'undefined' && !__SENTRY_BROWSER_BUNDLE__;
128
+ }
129
+ /**
130
+ * Figures out if we're building a browser bundle.
131
+ *
132
+ * @returns true if this is a browser bundle build.
133
+ */
134
+ function isBrowserBundle() {
135
+ return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;
136
+ }
137
+
244
138
  /**
245
139
  * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,
246
140
  * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.
@@ -251,7 +145,10 @@ var Sentry = (function (exports) {
251
145
  * @returns Answer to given question
252
146
  */
253
147
  function isNodeEnv() {
254
- return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
148
+ // explicitly check for browser bundles as those can be optimized statically
149
+ // by terser/rollup.
150
+ return (!isBrowserBundle() &&
151
+ Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]');
255
152
  }
256
153
  /**
257
154
  * Requires a module which is protected against bundler minification.
@@ -286,6 +183,8 @@ var Sentry = (function (exports) {
286
183
 
287
184
  /* eslint-disable @typescript-eslint/no-explicit-any */
288
185
  /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
186
+ // eslint-disable-next-line @typescript-eslint/unbound-method
187
+ var objectToString = Object.prototype.toString;
289
188
  /**
290
189
  * Checks whether given value's type is one of a few Error or Error-like
291
190
  * {@link isError}.
@@ -294,17 +193,18 @@ var Sentry = (function (exports) {
294
193
  * @returns A boolean representing the result.
295
194
  */
296
195
  function isError(wat) {
297
- switch (Object.prototype.toString.call(wat)) {
196
+ switch (objectToString.call(wat)) {
298
197
  case '[object Error]':
299
- return true;
300
198
  case '[object Exception]':
301
- return true;
302
199
  case '[object DOMException]':
303
200
  return true;
304
201
  default:
305
202
  return isInstanceOf(wat, Error);
306
203
  }
307
204
  }
205
+ function isBuiltin(wat, ty) {
206
+ return objectToString.call(wat) === "[object " + ty + "]";
207
+ }
308
208
  /**
309
209
  * Checks whether given value's type is ErrorEvent
310
210
  * {@link isErrorEvent}.
@@ -313,7 +213,7 @@ var Sentry = (function (exports) {
313
213
  * @returns A boolean representing the result.
314
214
  */
315
215
  function isErrorEvent(wat) {
316
- return Object.prototype.toString.call(wat) === '[object ErrorEvent]';
216
+ return isBuiltin(wat, 'ErrorEvent');
317
217
  }
318
218
  /**
319
219
  * Checks whether given value's type is DOMError
@@ -323,7 +223,7 @@ var Sentry = (function (exports) {
323
223
  * @returns A boolean representing the result.
324
224
  */
325
225
  function isDOMError(wat) {
326
- return Object.prototype.toString.call(wat) === '[object DOMError]';
226
+ return isBuiltin(wat, 'DOMError');
327
227
  }
328
228
  /**
329
229
  * Checks whether given value's type is DOMException
@@ -333,7 +233,7 @@ var Sentry = (function (exports) {
333
233
  * @returns A boolean representing the result.
334
234
  */
335
235
  function isDOMException(wat) {
336
- return Object.prototype.toString.call(wat) === '[object DOMException]';
236
+ return isBuiltin(wat, 'DOMException');
337
237
  }
338
238
  /**
339
239
  * Checks whether given value's type is a string
@@ -343,10 +243,10 @@ var Sentry = (function (exports) {
343
243
  * @returns A boolean representing the result.
344
244
  */
345
245
  function isString(wat) {
346
- return Object.prototype.toString.call(wat) === '[object String]';
246
+ return isBuiltin(wat, 'String');
347
247
  }
348
248
  /**
349
- * Checks whether given value's is a primitive (undefined, null, number, boolean, string, bigint, symbol)
249
+ * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)
350
250
  * {@link isPrimitive}.
351
251
  *
352
252
  * @param wat A value to be checked.
@@ -363,7 +263,7 @@ var Sentry = (function (exports) {
363
263
  * @returns A boolean representing the result.
364
264
  */
365
265
  function isPlainObject(wat) {
366
- return Object.prototype.toString.call(wat) === '[object Object]';
266
+ return isBuiltin(wat, 'Object');
367
267
  }
368
268
  /**
369
269
  * Checks whether given value's type is an Event instance
@@ -393,7 +293,7 @@ var Sentry = (function (exports) {
393
293
  * @returns A boolean representing the result.
394
294
  */
395
295
  function isRegExp(wat) {
396
- return Object.prototype.toString.call(wat) === '[object RegExp]';
296
+ return isBuiltin(wat, 'RegExp');
397
297
  }
398
298
  /**
399
299
  * Checks whether given value has a then function.
@@ -477,7 +377,6 @@ var Sentry = (function (exports) {
477
377
  * @returns generated DOM path
478
378
  */
479
379
  function _htmlElementAsString(el, keyAttrs) {
480
- var _a, _b;
481
380
  var elem = el;
482
381
  var out = [];
483
382
  var className;
@@ -490,9 +389,10 @@ var Sentry = (function (exports) {
490
389
  }
491
390
  out.push(elem.tagName.toLowerCase());
492
391
  // Pairs of attribute keys defined in `serializeAttribute` and their values on element.
493
- var keyAttrPairs = ((_a = keyAttrs) === null || _a === void 0 ? void 0 : _a.length) ? keyAttrs.filter(function (keyAttr) { return elem.getAttribute(keyAttr); }).map(function (keyAttr) { return [keyAttr, elem.getAttribute(keyAttr)]; })
392
+ var keyAttrPairs = keyAttrs && keyAttrs.length
393
+ ? keyAttrs.filter(function (keyAttr) { return elem.getAttribute(keyAttr); }).map(function (keyAttr) { return [keyAttr, elem.getAttribute(keyAttr)]; })
494
394
  : null;
495
- if ((_b = keyAttrPairs) === null || _b === void 0 ? void 0 : _b.length) {
395
+ if (keyAttrPairs && keyAttrPairs.length) {
496
396
  keyAttrPairs.forEach(function (keyAttrPair) {
497
397
  out.push("[" + keyAttrPair[0] + "=\"" + keyAttrPair[1] + "\"]");
498
398
  });
@@ -573,92 +473,89 @@ var Sentry = (function (exports) {
573
473
 
574
474
  /** Regular expression used to parse a Dsn. */
575
475
  var DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/;
576
- /** Error message */
577
- var ERROR_MESSAGE = 'Invalid Dsn';
578
- /** The Sentry Dsn, identifying a Sentry instance and project. */
579
- var Dsn = /** @class */ (function () {
580
- /** Creates a new Dsn component */
581
- function Dsn(from) {
582
- if (typeof from === 'string') {
583
- this._fromString(from);
584
- }
585
- else {
586
- this._fromComponents(from);
587
- }
588
- this._validate();
476
+ function isValidProtocol(protocol) {
477
+ return protocol === 'http' || protocol === 'https';
478
+ }
479
+ /**
480
+ * Renders the string representation of this Dsn.
481
+ *
482
+ * By default, this will render the public representation without the password
483
+ * component. To get the deprecated private representation, set `withPassword`
484
+ * to true.
485
+ *
486
+ * @param withPassword When set to true, the password will be included.
487
+ */
488
+ function dsnToString(dsn, withPassword) {
489
+ if (withPassword === void 0) { withPassword = false; }
490
+ var host = dsn.host, path = dsn.path, pass = dsn.pass, port = dsn.port, projectId = dsn.projectId, protocol = dsn.protocol, publicKey = dsn.publicKey;
491
+ return (protocol + "://" + publicKey + (withPassword && pass ? ":" + pass : '') +
492
+ ("@" + host + (port ? ":" + port : '') + "/" + (path ? path + "/" : path) + projectId));
493
+ }
494
+ function dsnFromString(str) {
495
+ var match = DSN_REGEX.exec(str);
496
+ if (!match) {
497
+ throw new SentryError("Invalid Sentry Dsn: " + str);
589
498
  }
590
- /**
591
- * Renders the string representation of this Dsn.
592
- *
593
- * By default, this will render the public representation without the password
594
- * component. To get the deprecated private representation, set `withPassword`
595
- * to true.
596
- *
597
- * @param withPassword When set to true, the password will be included.
598
- */
599
- Dsn.prototype.toString = function (withPassword) {
600
- if (withPassword === void 0) { withPassword = false; }
601
- var _a = this, host = _a.host, path = _a.path, pass = _a.pass, port = _a.port, projectId = _a.projectId, protocol = _a.protocol, publicKey = _a.publicKey;
602
- return (protocol + "://" + publicKey + (withPassword && pass ? ":" + pass : '') +
603
- ("@" + host + (port ? ":" + port : '') + "/" + (path ? path + "/" : path) + projectId));
604
- };
605
- /** Parses a string into this Dsn. */
606
- Dsn.prototype._fromString = function (str) {
607
- var match = DSN_REGEX.exec(str);
608
- if (!match) {
609
- throw new SentryError(ERROR_MESSAGE);
610
- }
611
- var _a = __read(match.slice(1), 6), protocol = _a[0], publicKey = _a[1], _b = _a[2], pass = _b === void 0 ? '' : _b, host = _a[3], _c = _a[4], port = _c === void 0 ? '' : _c, lastPath = _a[5];
612
- var path = '';
613
- var projectId = lastPath;
614
- var split = projectId.split('/');
615
- if (split.length > 1) {
616
- path = split.slice(0, -1).join('/');
617
- projectId = split.pop();
618
- }
619
- if (projectId) {
620
- var projectMatch = projectId.match(/^\d+/);
621
- if (projectMatch) {
622
- projectId = projectMatch[0];
623
- }
624
- }
625
- this._fromComponents({ host: host, pass: pass, path: path, projectId: projectId, port: port, protocol: protocol, publicKey: publicKey });
626
- };
627
- /** Maps Dsn components into this instance. */
628
- Dsn.prototype._fromComponents = function (components) {
629
- // TODO this is for backwards compatibility, and can be removed in a future version
630
- if ('user' in components && !('publicKey' in components)) {
631
- components.publicKey = components.user;
632
- }
633
- this.user = components.publicKey || '';
634
- this.protocol = components.protocol;
635
- this.publicKey = components.publicKey || '';
636
- this.pass = components.pass || '';
637
- this.host = components.host;
638
- this.port = components.port || '';
639
- this.path = components.path || '';
640
- this.projectId = components.projectId;
641
- };
642
- /** Validates this Dsn and throws on error. */
643
- Dsn.prototype._validate = function () {
644
- var _this = this;
645
- ['protocol', 'publicKey', 'host', 'projectId'].forEach(function (component) {
646
- if (!_this[component]) {
647
- throw new SentryError(ERROR_MESSAGE + ": " + component + " missing");
648
- }
649
- });
650
- if (!this.projectId.match(/^\d+$/)) {
651
- throw new SentryError(ERROR_MESSAGE + ": Invalid projectId " + this.projectId);
652
- }
653
- if (this.protocol !== 'http' && this.protocol !== 'https') {
654
- throw new SentryError(ERROR_MESSAGE + ": Invalid protocol " + this.protocol);
655
- }
656
- if (this.port && isNaN(parseInt(this.port, 10))) {
657
- throw new SentryError(ERROR_MESSAGE + ": Invalid port " + this.port);
499
+ var _a = __read(match.slice(1), 6), protocol = _a[0], publicKey = _a[1], _b = _a[2], pass = _b === void 0 ? '' : _b, host = _a[3], _c = _a[4], port = _c === void 0 ? '' : _c, lastPath = _a[5];
500
+ var path = '';
501
+ var projectId = lastPath;
502
+ var split = projectId.split('/');
503
+ if (split.length > 1) {
504
+ path = split.slice(0, -1).join('/');
505
+ projectId = split.pop();
506
+ }
507
+ if (projectId) {
508
+ var projectMatch = projectId.match(/^\d+/);
509
+ if (projectMatch) {
510
+ projectId = projectMatch[0];
658
511
  }
512
+ }
513
+ return dsnFromComponents({ host: host, pass: pass, path: path, projectId: projectId, port: port, protocol: protocol, publicKey: publicKey });
514
+ }
515
+ function dsnFromComponents(components) {
516
+ // TODO this is for backwards compatibility, and can be removed in a future version
517
+ if ('user' in components && !('publicKey' in components)) {
518
+ components.publicKey = components.user;
519
+ }
520
+ return {
521
+ user: components.publicKey || '',
522
+ protocol: components.protocol,
523
+ publicKey: components.publicKey || '',
524
+ pass: components.pass || '',
525
+ host: components.host,
526
+ port: components.port || '',
527
+ path: components.path || '',
528
+ projectId: components.projectId,
659
529
  };
660
- return Dsn;
661
- }());
530
+ }
531
+ function validateDsn(dsn) {
532
+ if (!isDebugBuild()) {
533
+ return;
534
+ }
535
+ var port = dsn.port, projectId = dsn.projectId, protocol = dsn.protocol;
536
+ var requiredComponents = ['protocol', 'publicKey', 'host', 'projectId'];
537
+ requiredComponents.forEach(function (component) {
538
+ if (!dsn[component]) {
539
+ throw new SentryError("Invalid Sentry Dsn: " + component + " missing");
540
+ }
541
+ });
542
+ if (!projectId.match(/^\d+$/)) {
543
+ throw new SentryError("Invalid Sentry Dsn: Invalid projectId " + projectId);
544
+ }
545
+ if (!isValidProtocol(protocol)) {
546
+ throw new SentryError("Invalid Sentry Dsn: Invalid protocol " + protocol);
547
+ }
548
+ if (port && isNaN(parseInt(port, 10))) {
549
+ throw new SentryError("Invalid Sentry Dsn: Invalid port " + port);
550
+ }
551
+ return true;
552
+ }
553
+ /** The Sentry Dsn, identifying a Sentry instance and project. */
554
+ function makeDsn(from) {
555
+ var components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);
556
+ validateDsn(components);
557
+ return components;
558
+ }
662
559
 
663
560
  // TODO: Implement different loggers for different environments
664
561
  var global$1 = getGlobalObject();
@@ -757,56 +654,45 @@ var Sentry = (function (exports) {
757
654
 
758
655
  /* eslint-disable @typescript-eslint/no-unsafe-member-access */
759
656
  /* eslint-disable @typescript-eslint/no-explicit-any */
760
- /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
761
657
  /**
762
- * Memo class used for decycle json objects. Uses WeakSet if available otherwise array.
658
+ * Helper to decycle json objects
763
659
  */
764
- var Memo = /** @class */ (function () {
765
- function Memo() {
766
- this._hasWeakSet = typeof WeakSet === 'function';
767
- this._inner = this._hasWeakSet ? new WeakSet() : [];
768
- }
769
- /**
770
- * Sets obj to remember.
771
- * @param obj Object to remember
772
- */
773
- Memo.prototype.memoize = function (obj) {
774
- if (this._hasWeakSet) {
775
- if (this._inner.has(obj)) {
660
+ function memoBuilder() {
661
+ var hasWeakSet = typeof WeakSet === 'function';
662
+ var inner = hasWeakSet ? new WeakSet() : [];
663
+ function memoize(obj) {
664
+ if (hasWeakSet) {
665
+ if (inner.has(obj)) {
776
666
  return true;
777
667
  }
778
- this._inner.add(obj);
668
+ inner.add(obj);
779
669
  return false;
780
670
  }
781
671
  // eslint-disable-next-line @typescript-eslint/prefer-for-of
782
- for (var i = 0; i < this._inner.length; i++) {
783
- var value = this._inner[i];
672
+ for (var i = 0; i < inner.length; i++) {
673
+ var value = inner[i];
784
674
  if (value === obj) {
785
675
  return true;
786
676
  }
787
677
  }
788
- this._inner.push(obj);
678
+ inner.push(obj);
789
679
  return false;
790
- };
791
- /**
792
- * Removes object from internal storage.
793
- * @param obj Object to forget
794
- */
795
- Memo.prototype.unmemoize = function (obj) {
796
- if (this._hasWeakSet) {
797
- this._inner.delete(obj);
680
+ }
681
+ function unmemoize(obj) {
682
+ if (hasWeakSet) {
683
+ inner.delete(obj);
798
684
  }
799
685
  else {
800
- for (var i = 0; i < this._inner.length; i++) {
801
- if (this._inner[i] === obj) {
802
- this._inner.splice(i, 1);
686
+ for (var i = 0; i < inner.length; i++) {
687
+ if (inner[i] === obj) {
688
+ inner.splice(i, 1);
803
689
  break;
804
690
  }
805
691
  }
806
692
  }
807
- };
808
- return Memo;
809
- }());
693
+ }
694
+ return [memoize, unmemoize];
695
+ }
810
696
 
811
697
  var defaultFunctionName = '<anonymous>';
812
698
  /**
@@ -903,13 +789,7 @@ var Sentry = (function (exports) {
903
789
  // otherwise it'll throw "TypeError: Object.defineProperties called on non-object"
904
790
  if (typeof wrapped === 'function') {
905
791
  try {
906
- wrapped.prototype = wrapped.prototype || {};
907
- Object.defineProperties(wrapped, {
908
- __sentry_original__: {
909
- enumerable: false,
910
- value: original,
911
- },
912
- });
792
+ markFunctionWrapped(wrapped, original);
913
793
  }
914
794
  catch (_Oo) {
915
795
  // This can throw if multiple fill happens on a global object like XMLHttpRequest
@@ -918,6 +798,41 @@ var Sentry = (function (exports) {
918
798
  }
919
799
  source[name] = wrapped;
920
800
  }
801
+ /**
802
+ * Defines a non enumerable property. This creates a non enumerable property on an object.
803
+ *
804
+ * @param func The function to set a property to
805
+ * @param name the name of the special sentry property
806
+ * @param value the property to define
807
+ */
808
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
809
+ function addNonEnumerableProperty(func, name, value) {
810
+ Object.defineProperty(func, name, {
811
+ value: value,
812
+ });
813
+ }
814
+ /**
815
+ * Remembers the original function on the wrapped function and
816
+ * patches up the prototype.
817
+ *
818
+ * @param wrapped the wrapper function
819
+ * @param original the original function that gets wrapped
820
+ */
821
+ function markFunctionWrapped(wrapped, original) {
822
+ var proto = original.prototype || {};
823
+ wrapped.prototype = original.prototype = proto;
824
+ addNonEnumerableProperty(wrapped, '__sentry_original__', original);
825
+ }
826
+ /**
827
+ * This extracts the original function if available. See
828
+ * `markFunctionWrapped` for more information.
829
+ *
830
+ * @param func the function to unwrap
831
+ * @returns the unwrapped version of the function if available.
832
+ */
833
+ function getOriginalFunction(func) {
834
+ return func.__sentry_original__;
835
+ }
921
836
  /**
922
837
  * Encodes given object into url-friendly format
923
838
  *
@@ -1018,11 +933,11 @@ var Sentry = (function (exports) {
1018
933
  * unchanged.
1019
934
  */
1020
935
  function serializeValue(value) {
1021
- var type = Object.prototype.toString.call(value);
1022
936
  // Node.js REPL notation
1023
937
  if (typeof value === 'string') {
1024
938
  return value;
1025
939
  }
940
+ var type = Object.prototype.toString.call(value);
1026
941
  if (type === '[object Object]') {
1027
942
  return '[Object]';
1028
943
  }
@@ -1094,8 +1009,8 @@ var Sentry = (function (exports) {
1094
1009
  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
1095
1010
  function walk(key, value, depth, memo) {
1096
1011
  if (depth === void 0) { depth = +Infinity; }
1097
- if (memo === void 0) { memo = new Memo(); }
1098
- // If we reach the maximum depth, serialize whatever has left
1012
+ if (memo === void 0) { memo = memoBuilder(); }
1013
+ // If we reach the maximum depth, serialize whatever is left
1099
1014
  if (depth === 0) {
1100
1015
  return serializeValue(value);
1101
1016
  }
@@ -1105,17 +1020,18 @@ var Sentry = (function (exports) {
1105
1020
  return value.toJSON();
1106
1021
  }
1107
1022
  /* eslint-enable @typescript-eslint/no-unsafe-member-access */
1108
- // If normalized value is a primitive, there are no branches left to walk, so we can just bail out, as theres no point in going down that branch any further
1023
+ // If normalized value is a primitive, there are no branches left to walk, so bail out
1109
1024
  var normalized = normalizeValue(value, key);
1110
1025
  if (isPrimitive(normalized)) {
1111
1026
  return normalized;
1112
1027
  }
1113
- // Create source that we will use for next itterations, either objectified error object (Error type with extracted keys:value pairs) or the input itself
1028
+ // Create source that we will use for the next iteration. It will either be an objectified error object (`Error` type
1029
+ // with extracted key:value pairs) or the input itself.
1114
1030
  var source = getWalkSource(value);
1115
1031
  // Create an accumulator that will act as a parent for all future itterations of that branch
1116
1032
  var acc = Array.isArray(value) ? [] : {};
1117
1033
  // If we already walked that branch, bail out, as it's circular reference
1118
- if (memo.memoize(value)) {
1034
+ if (memo[0](value)) {
1119
1035
  return '[Circular ~]';
1120
1036
  }
1121
1037
  // Walk all keys of the source
@@ -1128,7 +1044,7 @@ var Sentry = (function (exports) {
1128
1044
  acc[innerKey] = walk(innerKey, source[innerKey], depth - 1, memo);
1129
1045
  }
1130
1046
  // Once walked through all the branches, remove the parent from memo storage
1131
- memo.unmemoize(value);
1047
+ memo[1](value);
1132
1048
  // Return accumulated values
1133
1049
  return acc;
1134
1050
  }
@@ -1273,7 +1189,9 @@ var Sentry = (function (exports) {
1273
1189
  doc.head.removeChild(sandbox);
1274
1190
  }
1275
1191
  catch (err) {
1276
- logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);
1192
+ if (isDebugBuild()) {
1193
+ logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);
1194
+ }
1277
1195
  }
1278
1196
  }
1279
1197
  return result;
@@ -1285,9 +1203,9 @@ var Sentry = (function (exports) {
1285
1203
  * @returns Answer to the given question.
1286
1204
  */
1287
1205
  function supportsReferrerPolicy() {
1288
- // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default
1289
- // https://caniuse.com/#feat=referrer-policy
1290
- // It doesn't. And it throw exception instead of ignoring this parameter...
1206
+ // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'
1207
+ // (see https://caniuse.com/#feat=referrer-policy),
1208
+ // it doesn't. And it throws an exception instead of ignoring this parameter...
1291
1209
  // REF: https://github.com/getsentry/raven-js/issues/1233
1292
1210
  if (!supportsFetch()) {
1293
1211
  return false;
@@ -1372,13 +1290,10 @@ var Sentry = (function (exports) {
1372
1290
  * Use at your own risk, this might break without changelog notice, only used internally.
1373
1291
  * @hidden
1374
1292
  */
1375
- function addInstrumentationHandler(handler) {
1376
- if (!handler || typeof handler.type !== 'string' || typeof handler.callback !== 'function') {
1377
- return;
1378
- }
1379
- handlers[handler.type] = handlers[handler.type] || [];
1380
- handlers[handler.type].push(handler.callback);
1381
- instrument(handler.type);
1293
+ function addInstrumentationHandler(type, callback) {
1294
+ handlers[type] = handlers[type] || [];
1295
+ handlers[type].push(callback);
1296
+ instrument(type);
1382
1297
  }
1383
1298
  /** JSDoc */
1384
1299
  function triggerHandlers(type, data) {
@@ -1393,7 +1308,9 @@ var Sentry = (function (exports) {
1393
1308
  handler(data);
1394
1309
  }
1395
1310
  catch (e) {
1396
- logger.error("Error while triggering instrumentation handler.\nType: " + type + "\nName: " + getFunctionName(handler) + "\nError: " + e);
1311
+ if (isDebugBuild()) {
1312
+ logger.error("Error while triggering instrumentation handler.\nType: " + type + "\nName: " + getFunctionName(handler) + "\nError: " + e);
1313
+ }
1397
1314
  }
1398
1315
  }
1399
1316
  }
@@ -1492,9 +1409,6 @@ var Sentry = (function (exports) {
1492
1409
  if (!('XMLHttpRequest' in global$2)) {
1493
1410
  return;
1494
1411
  }
1495
- // Poor man's implementation of ES6 `Map`, tracking and keeping in sync key and value separately.
1496
- var requestKeys = [];
1497
- var requestValues = [];
1498
1412
  var xhrproto = XMLHttpRequest.prototype;
1499
1413
  fill(xhrproto, 'open', function (originalOpen) {
1500
1414
  return function () {
@@ -1505,14 +1419,14 @@ var Sentry = (function (exports) {
1505
1419
  // eslint-disable-next-line @typescript-eslint/no-this-alias
1506
1420
  var xhr = this;
1507
1421
  var url = args[1];
1508
- xhr.__sentry_xhr__ = {
1422
+ var xhrInfo = (xhr.__sentry_xhr__ = {
1509
1423
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1510
1424
  method: isString(args[0]) ? args[0].toUpperCase() : args[0],
1511
1425
  url: args[1],
1512
- };
1426
+ });
1513
1427
  // if Sentry key appears in URL, don't capture it as a request
1514
1428
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1515
- if (isString(url) && xhr.__sentry_xhr__.method === 'POST' && url.match(/sentry_key/)) {
1429
+ if (isString(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) {
1516
1430
  xhr.__sentry_own_request__ = true;
1517
1431
  }
1518
1432
  var onreadystatechangeHandler = function () {
@@ -1520,23 +1434,7 @@ var Sentry = (function (exports) {
1520
1434
  try {
1521
1435
  // touching statusCode in some platforms throws
1522
1436
  // an exception
1523
- if (xhr.__sentry_xhr__) {
1524
- xhr.__sentry_xhr__.status_code = xhr.status;
1525
- }
1526
- }
1527
- catch (e) {
1528
- /* do nothing */
1529
- }
1530
- try {
1531
- var requestPos = requestKeys.indexOf(xhr);
1532
- if (requestPos !== -1) {
1533
- // Make sure to pop both key and value to keep it in sync.
1534
- requestKeys.splice(requestPos);
1535
- var args_1 = requestValues.splice(requestPos)[0];
1536
- if (xhr.__sentry_xhr__ && args_1[0] !== undefined) {
1537
- xhr.__sentry_xhr__.body = args_1[0];
1538
- }
1539
- }
1437
+ xhrInfo.status_code = xhr.status;
1540
1438
  }
1541
1439
  catch (e) {
1542
1440
  /* do nothing */
@@ -1573,8 +1471,9 @@ var Sentry = (function (exports) {
1573
1471
  for (var _i = 0; _i < arguments.length; _i++) {
1574
1472
  args[_i] = arguments[_i];
1575
1473
  }
1576
- requestKeys.push(this);
1577
- requestValues.push(args);
1474
+ if (this.__sentry_xhr__ && args[0] !== undefined) {
1475
+ this.__sentry_xhr__.body = args[0];
1476
+ }
1578
1477
  triggerHandlers('xhr', {
1579
1478
  args: args,
1580
1479
  startTimestamp: Date.now(),
@@ -1918,22 +1817,26 @@ var Sentry = (function (exports) {
1918
1817
  relative: match[5] + query + fragment,
1919
1818
  };
1920
1819
  }
1820
+ function getFirstException(event) {
1821
+ return event.exception && event.exception.values ? event.exception.values[0] : undefined;
1822
+ }
1921
1823
  /**
1922
1824
  * Extracts either message or type+value from an event that can be used for user-facing logs
1923
1825
  * @returns event's description
1924
1826
  */
1925
1827
  function getEventDescription(event) {
1926
- if (event.message) {
1927
- return event.message;
1828
+ var message = event.message, eventId = event.event_id;
1829
+ if (message) {
1830
+ return message;
1928
1831
  }
1929
- if (event.exception && event.exception.values && event.exception.values[0]) {
1930
- var exception = event.exception.values[0];
1931
- if (exception.type && exception.value) {
1932
- return exception.type + ": " + exception.value;
1832
+ var firstException = getFirstException(event);
1833
+ if (firstException) {
1834
+ if (firstException.type && firstException.value) {
1835
+ return firstException.type + ": " + firstException.value;
1933
1836
  }
1934
- return exception.type || exception.value || event.event_id || '<unknown>';
1837
+ return firstException.type || firstException.value || eventId || '<unknown>';
1935
1838
  }
1936
- return event.event_id || '<unknown>';
1839
+ return eventId || '<unknown>';
1937
1840
  }
1938
1841
  /**
1939
1842
  * Adds exception values, type and value to an synthetic Exception.
@@ -1943,11 +1846,15 @@ var Sentry = (function (exports) {
1943
1846
  * @hidden
1944
1847
  */
1945
1848
  function addExceptionTypeValue(event, value, type) {
1946
- event.exception = event.exception || {};
1947
- event.exception.values = event.exception.values || [];
1948
- event.exception.values[0] = event.exception.values[0] || {};
1949
- event.exception.values[0].value = event.exception.values[0].value || value || '';
1950
- event.exception.values[0].type = event.exception.values[0].type || type || 'Error';
1849
+ var exception = (event.exception = event.exception || {});
1850
+ var values = (exception.values = exception.values || []);
1851
+ var firstException = (values[0] = values[0] || {});
1852
+ if (!firstException.value) {
1853
+ firstException.value = value || '';
1854
+ }
1855
+ if (!firstException.type) {
1856
+ firstException.type = type || 'Error';
1857
+ }
1951
1858
  }
1952
1859
  /**
1953
1860
  * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.
@@ -1957,17 +1864,16 @@ var Sentry = (function (exports) {
1957
1864
  * @hidden
1958
1865
  */
1959
1866
  function addExceptionMechanism(event, newMechanism) {
1960
- var _a;
1961
- if (!event.exception || !event.exception.values) {
1867
+ var firstException = getFirstException(event);
1868
+ if (!firstException) {
1962
1869
  return;
1963
1870
  }
1964
- var exceptionValue0 = event.exception.values[0];
1965
1871
  var defaultMechanism = { type: 'generic', handled: true };
1966
- var currentMechanism = exceptionValue0.mechanism;
1967
- exceptionValue0.mechanism = __assign(__assign(__assign({}, defaultMechanism), currentMechanism), newMechanism);
1872
+ var currentMechanism = firstException.mechanism;
1873
+ firstException.mechanism = __assign(__assign(__assign({}, defaultMechanism), currentMechanism), newMechanism);
1968
1874
  if (newMechanism && 'data' in newMechanism) {
1969
- var mergedData = __assign(__assign({}, (_a = currentMechanism) === null || _a === void 0 ? void 0 : _a.data), newMechanism.data);
1970
- exceptionValue0.mechanism.data = mergedData;
1875
+ var mergedData = __assign(__assign({}, (currentMechanism && currentMechanism.data)), newMechanism.data);
1876
+ firstException.mechanism.data = mergedData;
1971
1877
  }
1972
1878
  }
1973
1879
  var defaultRetryAfter = 60 * 1000; // 60 seconds
@@ -2012,17 +1918,14 @@ var Sentry = (function (exports) {
2012
1918
  * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)
2013
1919
  */
2014
1920
  function checkOrSetAlreadyCaught(exception) {
2015
- var _a;
2016
1921
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
2017
- if ((_a = exception) === null || _a === void 0 ? void 0 : _a.__sentry_captured__) {
1922
+ if (exception && exception.__sentry_captured__) {
2018
1923
  return true;
2019
1924
  }
2020
1925
  try {
2021
1926
  // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the
2022
1927
  // `ExtraErrorData` integration
2023
- Object.defineProperty(exception, '__sentry_captured__', {
2024
- value: true,
2025
- });
1928
+ addNonEnumerableProperty(exception, '__sentry_captured__', true);
2026
1929
  }
2027
1930
  catch (err) {
2028
1931
  // `exception` is a primitive, so we can't mark it seen
@@ -2031,6 +1934,28 @@ var Sentry = (function (exports) {
2031
1934
  }
2032
1935
 
2033
1936
  /* eslint-disable @typescript-eslint/explicit-function-return-type */
1937
+ /**
1938
+ * Creates a resolved sync promise.
1939
+ *
1940
+ * @param value the value to resolve the promise with
1941
+ * @returns the resolved sync promise
1942
+ */
1943
+ function resolvedSyncPromise(value) {
1944
+ return new SyncPromise(function (resolve) {
1945
+ resolve(value);
1946
+ });
1947
+ }
1948
+ /**
1949
+ * Creates a rejected sync promise.
1950
+ *
1951
+ * @param value the value to reject the promise with
1952
+ * @returns the rejected sync promise
1953
+ */
1954
+ function rejectedSyncPromise(reason) {
1955
+ return new SyncPromise(function (_, reject) {
1956
+ reject(reason);
1957
+ });
1958
+ }
2034
1959
  /**
2035
1960
  * Thenable class that behaves like a Promise and follows it's interface
2036
1961
  * but is not async internally
@@ -2038,19 +1963,19 @@ var Sentry = (function (exports) {
2038
1963
  var SyncPromise = /** @class */ (function () {
2039
1964
  function SyncPromise(executor) {
2040
1965
  var _this = this;
2041
- this._state = "PENDING" /* PENDING */;
1966
+ this._state = 0 /* PENDING */;
2042
1967
  this._handlers = [];
2043
1968
  /** JSDoc */
2044
1969
  this._resolve = function (value) {
2045
- _this._setResult("RESOLVED" /* RESOLVED */, value);
1970
+ _this._setResult(1 /* RESOLVED */, value);
2046
1971
  };
2047
1972
  /** JSDoc */
2048
1973
  this._reject = function (reason) {
2049
- _this._setResult("REJECTED" /* REJECTED */, reason);
1974
+ _this._setResult(2 /* REJECTED */, reason);
2050
1975
  };
2051
1976
  /** JSDoc */
2052
1977
  this._setResult = function (state, value) {
2053
- if (_this._state !== "PENDING" /* PENDING */) {
1978
+ if (_this._state !== 0 /* PENDING */) {
2054
1979
  return;
2055
1980
  }
2056
1981
  if (isThenable(value)) {
@@ -2061,35 +1986,25 @@ var Sentry = (function (exports) {
2061
1986
  _this._value = value;
2062
1987
  _this._executeHandlers();
2063
1988
  };
2064
- // TODO: FIXME
2065
- /** JSDoc */
2066
- this._attachHandler = function (handler) {
2067
- _this._handlers = _this._handlers.concat(handler);
2068
- _this._executeHandlers();
2069
- };
2070
1989
  /** JSDoc */
2071
1990
  this._executeHandlers = function () {
2072
- if (_this._state === "PENDING" /* PENDING */) {
1991
+ if (_this._state === 0 /* PENDING */) {
2073
1992
  return;
2074
1993
  }
2075
1994
  var cachedHandlers = _this._handlers.slice();
2076
1995
  _this._handlers = [];
2077
1996
  cachedHandlers.forEach(function (handler) {
2078
- if (handler.done) {
1997
+ if (handler[0]) {
2079
1998
  return;
2080
1999
  }
2081
- if (_this._state === "RESOLVED" /* RESOLVED */) {
2082
- if (handler.onfulfilled) {
2083
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
2084
- handler.onfulfilled(_this._value);
2085
- }
2000
+ if (_this._state === 1 /* RESOLVED */) {
2001
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
2002
+ handler[1](_this._value);
2086
2003
  }
2087
- if (_this._state === "REJECTED" /* REJECTED */) {
2088
- if (handler.onrejected) {
2089
- handler.onrejected(_this._value);
2090
- }
2004
+ if (_this._state === 2 /* REJECTED */) {
2005
+ handler[2](_this._value);
2091
2006
  }
2092
- handler.done = true;
2007
+ handler[0] = true;
2093
2008
  });
2094
2009
  };
2095
2010
  try {
@@ -2100,81 +2015,41 @@ var Sentry = (function (exports) {
2100
2015
  }
2101
2016
  }
2102
2017
  /** JSDoc */
2103
- SyncPromise.resolve = function (value) {
2104
- return new SyncPromise(function (resolve) {
2105
- resolve(value);
2106
- });
2107
- };
2108
- /** JSDoc */
2109
- SyncPromise.reject = function (reason) {
2110
- return new SyncPromise(function (_, reject) {
2111
- reject(reason);
2112
- });
2113
- };
2114
- /** JSDoc */
2115
- SyncPromise.all = function (collection) {
2116
- return new SyncPromise(function (resolve, reject) {
2117
- if (!Array.isArray(collection)) {
2118
- reject(new TypeError("Promise.all requires an array as input."));
2119
- return;
2120
- }
2121
- if (collection.length === 0) {
2122
- resolve([]);
2123
- return;
2124
- }
2125
- var counter = collection.length;
2126
- var resolvedCollection = [];
2127
- collection.forEach(function (item, index) {
2128
- void SyncPromise.resolve(item)
2129
- .then(function (value) {
2130
- resolvedCollection[index] = value;
2131
- counter -= 1;
2132
- if (counter !== 0) {
2133
- return;
2134
- }
2135
- resolve(resolvedCollection);
2136
- })
2137
- .then(null, reject);
2138
- });
2139
- });
2140
- };
2141
- /** JSDoc */
2142
2018
  SyncPromise.prototype.then = function (onfulfilled, onrejected) {
2143
2019
  var _this = this;
2144
2020
  return new SyncPromise(function (resolve, reject) {
2145
- _this._attachHandler({
2146
- done: false,
2147
- onfulfilled: function (result) {
2021
+ _this._handlers.push([
2022
+ false,
2023
+ function (result) {
2148
2024
  if (!onfulfilled) {
2149
2025
  // TODO: ¯\_(ツ)_/¯
2150
2026
  // TODO: FIXME
2151
2027
  resolve(result);
2152
- return;
2153
- }
2154
- try {
2155
- resolve(onfulfilled(result));
2156
- return;
2157
2028
  }
2158
- catch (e) {
2159
- reject(e);
2160
- return;
2029
+ else {
2030
+ try {
2031
+ resolve(onfulfilled(result));
2032
+ }
2033
+ catch (e) {
2034
+ reject(e);
2035
+ }
2161
2036
  }
2162
2037
  },
2163
- onrejected: function (reason) {
2038
+ function (reason) {
2164
2039
  if (!onrejected) {
2165
2040
  reject(reason);
2166
- return;
2167
2041
  }
2168
- try {
2169
- resolve(onrejected(reason));
2170
- return;
2171
- }
2172
- catch (e) {
2173
- reject(e);
2174
- return;
2042
+ else {
2043
+ try {
2044
+ resolve(onrejected(reason));
2045
+ }
2046
+ catch (e) {
2047
+ reject(e);
2048
+ }
2175
2049
  }
2176
2050
  },
2177
- });
2051
+ ]);
2052
+ _this._executeHandlers();
2178
2053
  });
2179
2054
  };
2180
2055
  /** JSDoc */
@@ -2208,26 +2083,27 @@ var Sentry = (function (exports) {
2208
2083
  });
2209
2084
  });
2210
2085
  };
2211
- /** JSDoc */
2212
- SyncPromise.prototype.toString = function () {
2213
- return '[object SyncPromise]';
2214
- };
2215
2086
  return SyncPromise;
2216
2087
  }());
2217
2088
 
2218
- /** A simple queue that holds promises. */
2219
- var PromiseBuffer = /** @class */ (function () {
2220
- function PromiseBuffer(_limit) {
2221
- this._limit = _limit;
2222
- /** Internal set of queued Promises */
2223
- this._buffer = [];
2089
+ /**
2090
+ * Creates an new PromiseBuffer object with the specified limit
2091
+ * @param limit max number of promises that can be stored in the buffer
2092
+ */
2093
+ function makePromiseBuffer(limit) {
2094
+ var buffer = [];
2095
+ function isReady() {
2096
+ return limit === undefined || buffer.length < limit;
2224
2097
  }
2225
2098
  /**
2226
- * Says if the buffer is ready to take more requests
2099
+ * Remove a promise from the queue.
2100
+ *
2101
+ * @param task Can be any PromiseLike<T>
2102
+ * @returns Removed promise.
2227
2103
  */
2228
- PromiseBuffer.prototype.isReady = function () {
2229
- return this._limit === undefined || this.length() < this._limit;
2230
- };
2104
+ function remove(task) {
2105
+ return buffer.splice(buffer.indexOf(task), 1)[0];
2106
+ }
2231
2107
  /**
2232
2108
  * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.
2233
2109
  *
@@ -2238,44 +2114,27 @@ var Sentry = (function (exports) {
2238
2114
  * limit check.
2239
2115
  * @returns The original promise.
2240
2116
  */
2241
- PromiseBuffer.prototype.add = function (taskProducer) {
2242
- var _this = this;
2243
- if (!this.isReady()) {
2244
- return SyncPromise.reject(new SentryError('Not adding Promise due to buffer limit reached.'));
2117
+ function add(taskProducer) {
2118
+ if (!isReady()) {
2119
+ return rejectedSyncPromise(new SentryError('Not adding Promise due to buffer limit reached.'));
2245
2120
  }
2246
2121
  // start the task and add its promise to the queue
2247
2122
  var task = taskProducer();
2248
- if (this._buffer.indexOf(task) === -1) {
2249
- this._buffer.push(task);
2123
+ if (buffer.indexOf(task) === -1) {
2124
+ buffer.push(task);
2250
2125
  }
2251
2126
  void task
2252
- .then(function () { return _this.remove(task); })
2127
+ .then(function () { return remove(task); })
2253
2128
  // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`
2254
2129
  // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't
2255
2130
  // have promises, so TS has to polyfill when down-compiling.)
2256
2131
  .then(null, function () {
2257
- return _this.remove(task).then(null, function () {
2258
- // We have to add another catch here because `this.remove()` starts a new promise chain.
2132
+ return remove(task).then(null, function () {
2133
+ // We have to add another catch here because `remove()` starts a new promise chain.
2259
2134
  });
2260
2135
  });
2261
2136
  return task;
2262
- };
2263
- /**
2264
- * Remove a promise from the queue.
2265
- *
2266
- * @param task Can be any PromiseLike<T>
2267
- * @returns Removed promise.
2268
- */
2269
- PromiseBuffer.prototype.remove = function (task) {
2270
- var removedTask = this._buffer.splice(this._buffer.indexOf(task), 1)[0];
2271
- return removedTask;
2272
- };
2273
- /**
2274
- * This function returns the number of unresolved promises in the queue.
2275
- */
2276
- PromiseBuffer.prototype.length = function () {
2277
- return this._buffer.length;
2278
- };
2137
+ }
2279
2138
  /**
2280
2139
  * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.
2281
2140
  *
@@ -2285,9 +2144,12 @@ var Sentry = (function (exports) {
2285
2144
  * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and
2286
2145
  * `false` otherwise
2287
2146
  */
2288
- PromiseBuffer.prototype.drain = function (timeout) {
2289
- var _this = this;
2290
- return new SyncPromise(function (resolve) {
2147
+ function drain(timeout) {
2148
+ return new SyncPromise(function (resolve, reject) {
2149
+ var counter = buffer.length;
2150
+ if (!counter) {
2151
+ return resolve(true);
2152
+ }
2291
2153
  // wait for `timeout` ms and then resolve to `false` (if not cancelled first)
2292
2154
  var capturedSetTimeout = setTimeout(function () {
2293
2155
  if (timeout && timeout > 0) {
@@ -2295,18 +2157,63 @@ var Sentry = (function (exports) {
2295
2157
  }
2296
2158
  }, timeout);
2297
2159
  // if all promises resolve in time, cancel the timer and resolve to `true`
2298
- void SyncPromise.all(_this._buffer)
2299
- .then(function () {
2300
- clearTimeout(capturedSetTimeout);
2301
- resolve(true);
2302
- })
2303
- .then(null, function () {
2304
- resolve(true);
2160
+ buffer.forEach(function (item) {
2161
+ void resolvedSyncPromise(item).then(function () {
2162
+ // eslint-disable-next-line no-plusplus
2163
+ if (!--counter) {
2164
+ clearTimeout(capturedSetTimeout);
2165
+ resolve(true);
2166
+ }
2167
+ }, reject);
2305
2168
  });
2306
2169
  });
2170
+ }
2171
+ return {
2172
+ $: buffer,
2173
+ add: add,
2174
+ drain: drain,
2307
2175
  };
2308
- return PromiseBuffer;
2309
- }());
2176
+ }
2177
+
2178
+ function isSupportedSeverity(level) {
2179
+ return SeverityLevels.indexOf(level) !== -1;
2180
+ }
2181
+ /**
2182
+ * Converts a string-based level into a {@link Severity}.
2183
+ *
2184
+ * @param level string representation of Severity
2185
+ * @returns Severity
2186
+ */
2187
+ function severityFromString(level) {
2188
+ if (level === 'warn')
2189
+ return exports.Severity.Warning;
2190
+ if (isSupportedSeverity(level)) {
2191
+ return level;
2192
+ }
2193
+ return exports.Severity.Log;
2194
+ }
2195
+
2196
+ /**
2197
+ * Converts an HTTP status code to sentry status {@link EventStatus}.
2198
+ *
2199
+ * @param code number HTTP status code
2200
+ * @returns EventStatus
2201
+ */
2202
+ function eventStatusFromHttpCode(code) {
2203
+ if (code >= 200 && code < 300) {
2204
+ return 'success';
2205
+ }
2206
+ if (code === 429) {
2207
+ return 'rate_limit';
2208
+ }
2209
+ if (code >= 400 && code < 500) {
2210
+ return 'invalid';
2211
+ }
2212
+ if (code >= 500) {
2213
+ return 'failed';
2214
+ }
2215
+ return 'unknown';
2216
+ }
2310
2217
 
2311
2218
  /**
2312
2219
  * A TimestampSource implementation for environments that do not support the Performance Web API natively.
@@ -2464,6 +2371,11 @@ var Sentry = (function (exports) {
2464
2371
  this._extra = {};
2465
2372
  /** Contexts */
2466
2373
  this._contexts = {};
2374
+ /**
2375
+ * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get
2376
+ * sent to Sentry
2377
+ */
2378
+ this._sdkProcessingMetadata = {};
2467
2379
  }
2468
2380
  /**
2469
2381
  * Inherit values from the parent scope.
@@ -2629,19 +2541,10 @@ var Sentry = (function (exports) {
2629
2541
  * @inheritDoc
2630
2542
  */
2631
2543
  Scope.prototype.getTransaction = function () {
2632
- var _a, _b, _c, _d;
2633
- // often, this span will be a transaction, but it's not guaranteed to be
2544
+ // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will
2545
+ // have a pointer to the currently-active transaction.
2634
2546
  var span = this.getSpan();
2635
- // try it the new way first
2636
- if ((_a = span) === null || _a === void 0 ? void 0 : _a.transaction) {
2637
- return (_b = span) === null || _b === void 0 ? void 0 : _b.transaction;
2638
- }
2639
- // fallback to the old way (known bug: this only finds transactions with sampled = true)
2640
- if ((_d = (_c = span) === null || _c === void 0 ? void 0 : _c.spanRecorder) === null || _d === void 0 ? void 0 : _d.spans[0]) {
2641
- return span.spanRecorder.spans[0];
2642
- }
2643
- // neither way found a transaction
2644
- return undefined;
2547
+ return span && span.transaction;
2645
2548
  };
2646
2549
  /**
2647
2550
  * @inheritDoc
@@ -2760,7 +2663,6 @@ var Sentry = (function (exports) {
2760
2663
  * @hidden
2761
2664
  */
2762
2665
  Scope.prototype.applyToEvent = function (event, hint) {
2763
- var _a;
2764
2666
  if (this._extra && Object.keys(this._extra).length) {
2765
2667
  event.extra = __assign(__assign({}, this._extra), event.extra);
2766
2668
  }
@@ -2784,7 +2686,7 @@ var Sentry = (function (exports) {
2784
2686
  // errors with transaction and it relies on that.
2785
2687
  if (this._span) {
2786
2688
  event.contexts = __assign({ trace: this._span.getTraceContext() }, event.contexts);
2787
- var transactionName = (_a = this._span.transaction) === null || _a === void 0 ? void 0 : _a.name;
2689
+ var transactionName = this._span.transaction && this._span.transaction.name;
2788
2690
  if (transactionName) {
2789
2691
  event.tags = __assign({ transaction: transactionName }, event.tags);
2790
2692
  }
@@ -2792,8 +2694,16 @@ var Sentry = (function (exports) {
2792
2694
  this._applyFingerprint(event);
2793
2695
  event.breadcrumbs = __spread((event.breadcrumbs || []), this._breadcrumbs);
2794
2696
  event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;
2697
+ event.sdkProcessingMetadata = this._sdkProcessingMetadata;
2795
2698
  return this._notifyEventProcessors(__spread(getGlobalEventProcessors(), this._eventProcessors), event, hint);
2796
2699
  };
2700
+ /**
2701
+ * Add data which will be accessible during event processing but won't get sent to Sentry
2702
+ */
2703
+ Scope.prototype.setSDKProcessingMetadata = function (newData) {
2704
+ this._sdkProcessingMetadata = __assign(__assign({}, this._sdkProcessingMetadata), newData);
2705
+ return this;
2706
+ };
2797
2707
  /**
2798
2708
  * This will be called after {@link applyToEvent} is finished.
2799
2709
  */
@@ -2885,7 +2795,7 @@ var Sentry = (function (exports) {
2885
2795
  this.errors = 0;
2886
2796
  this.sid = uuid4();
2887
2797
  this.duration = 0;
2888
- this.status = SessionStatus.Ok;
2798
+ this.status = 'ok';
2889
2799
  this.init = true;
2890
2800
  this.ignoreDuration = false;
2891
2801
  // Both timestamp and started are in seconds since the UNIX epoch.
@@ -2959,8 +2869,8 @@ var Sentry = (function (exports) {
2959
2869
  if (status) {
2960
2870
  this.update({ status: status });
2961
2871
  }
2962
- else if (this.status === SessionStatus.Ok) {
2963
- this.update({ status: SessionStatus.Exited });
2872
+ else if (this.status === 'ok') {
2873
+ this.update({ status: 'exited' });
2964
2874
  }
2965
2875
  else {
2966
2876
  this.update();
@@ -2978,12 +2888,12 @@ var Sentry = (function (exports) {
2978
2888
  errors: this.errors,
2979
2889
  did: typeof this.did === 'number' || typeof this.did === 'string' ? "" + this.did : undefined,
2980
2890
  duration: this.duration,
2981
- attrs: dropUndefinedKeys({
2891
+ attrs: {
2982
2892
  release: this.release,
2983
2893
  environment: this.environment,
2984
2894
  ip_address: this.ipAddress,
2985
2895
  user_agent: this.userAgent,
2986
- }),
2896
+ },
2987
2897
  });
2988
2898
  };
2989
2899
  return Session;
@@ -3301,11 +3211,17 @@ var Sentry = (function (exports) {
3301
3211
  * @inheritDoc
3302
3212
  */
3303
3213
  Hub.prototype.endSession = function () {
3304
- var _a, _b, _c, _d, _e;
3305
- (_c = (_b = (_a = this.getStackTop()) === null || _a === void 0 ? void 0 : _a.scope) === null || _b === void 0 ? void 0 : _b.getSession()) === null || _c === void 0 ? void 0 : _c.close();
3214
+ var layer = this.getStackTop();
3215
+ var scope = layer && layer.scope;
3216
+ var session = scope && scope.getSession();
3217
+ if (session) {
3218
+ session.close();
3219
+ }
3306
3220
  this._sendSessionUpdate();
3307
3221
  // the session is over; take it off of the scope
3308
- (_e = (_d = this.getStackTop()) === null || _d === void 0 ? void 0 : _d.scope) === null || _e === void 0 ? void 0 : _e.setSession();
3222
+ if (scope) {
3223
+ scope.setSession();
3224
+ }
3309
3225
  };
3310
3226
  /**
3311
3227
  * @inheritDoc
@@ -3321,8 +3237,8 @@ var Sentry = (function (exports) {
3321
3237
  if (scope) {
3322
3238
  // End existing session if there's one
3323
3239
  var currentSession = scope.getSession && scope.getSession();
3324
- if (currentSession && currentSession.status === SessionStatus.Ok) {
3325
- currentSession.update({ status: SessionStatus.Exited });
3240
+ if (currentSession && currentSession.status === 'ok') {
3241
+ currentSession.update({ status: 'exited' });
3326
3242
  }
3327
3243
  this.endSession();
3328
3244
  // Afterwards we set the new session on the scope
@@ -3434,9 +3350,9 @@ var Sentry = (function (exports) {
3434
3350
  * @returns discovered hub
3435
3351
  */
3436
3352
  function getHubFromActiveDomain(registry) {
3437
- var _a, _b, _c;
3438
3353
  try {
3439
- var activeDomain = (_c = (_b = (_a = getMainCarrier().__SENTRY__) === null || _a === void 0 ? void 0 : _a.extensions) === null || _b === void 0 ? void 0 : _b.domain) === null || _c === void 0 ? void 0 : _c.active;
3354
+ var sentry = getMainCarrier().__SENTRY__;
3355
+ var activeDomain = sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;
3440
3356
  // If there's no active domain, just return global hub
3441
3357
  if (!activeDomain) {
3442
3358
  return getHubFromCarrier(registry);
@@ -3531,7 +3447,7 @@ var Sentry = (function (exports) {
3531
3447
  * Captures a message event and sends it to Sentry.
3532
3448
  *
3533
3449
  * @param message The message to send to Sentry.
3534
- * @param level Define the level of the message.
3450
+ * @param Severity Define the level of the message.
3535
3451
  * @returns The generated eventId.
3536
3452
  */
3537
3453
  function captureMessage(message, captureContext) {
@@ -3663,138 +3579,84 @@ var Sentry = (function (exports) {
3663
3579
  }
3664
3580
 
3665
3581
  var SENTRY_API_VERSION = '7';
3666
- /**
3667
- * Helper class to provide urls, headers and metadata that can be used to form
3668
- * different types of requests to Sentry endpoints.
3669
- * Supports both envelopes and regular event requests.
3670
- **/
3671
- var API = /** @class */ (function () {
3672
- /** Create a new instance of API */
3673
- function API(dsn, metadata, tunnel) {
3674
- if (metadata === void 0) { metadata = {}; }
3675
- this.dsn = dsn;
3676
- this._dsnObject = new Dsn(dsn);
3677
- this.metadata = metadata;
3678
- this._tunnel = tunnel;
3679
- }
3680
- /** Returns the Dsn object. */
3681
- API.prototype.getDsn = function () {
3682
- return this._dsnObject;
3683
- };
3684
- /** Does this transport force envelopes? */
3685
- API.prototype.forceEnvelope = function () {
3686
- return !!this._tunnel;
3687
- };
3688
- /** Returns the prefix to construct Sentry ingestion API endpoints. */
3689
- API.prototype.getBaseApiEndpoint = function () {
3690
- var dsn = this.getDsn();
3691
- var protocol = dsn.protocol ? dsn.protocol + ":" : '';
3692
- var port = dsn.port ? ":" + dsn.port : '';
3693
- return protocol + "//" + dsn.host + port + (dsn.path ? "/" + dsn.path : '') + "/api/";
3694
- };
3695
- /** Returns the store endpoint URL. */
3696
- API.prototype.getStoreEndpoint = function () {
3697
- return this._getIngestEndpoint('store');
3698
- };
3699
- /**
3700
- * Returns the store endpoint URL with auth in the query string.
3701
- *
3702
- * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.
3703
- */
3704
- API.prototype.getStoreEndpointWithUrlEncodedAuth = function () {
3705
- return this.getStoreEndpoint() + "?" + this._encodedAuth();
3706
- };
3707
- /**
3708
- * Returns the envelope endpoint URL with auth in the query string.
3709
- *
3710
- * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.
3711
- */
3712
- API.prototype.getEnvelopeEndpointWithUrlEncodedAuth = function () {
3713
- if (this.forceEnvelope()) {
3714
- return this._tunnel;
3715
- }
3716
- return this._getEnvelopeEndpoint() + "?" + this._encodedAuth();
3717
- };
3718
- /** Returns only the path component for the store endpoint. */
3719
- API.prototype.getStoreEndpointPath = function () {
3720
- var dsn = this.getDsn();
3721
- return (dsn.path ? "/" + dsn.path : '') + "/api/" + dsn.projectId + "/store/";
3582
+ /** Initializes API Details */
3583
+ function initAPIDetails(dsn, metadata, tunnel) {
3584
+ return {
3585
+ initDsn: dsn,
3586
+ metadata: metadata || {},
3587
+ dsn: makeDsn(dsn),
3588
+ tunnel: tunnel,
3722
3589
  };
3723
- /**
3724
- * Returns an object that can be used in request headers.
3725
- * This is needed for node and the old /store endpoint in sentry
3726
- */
3727
- API.prototype.getRequestHeaders = function (clientName, clientVersion) {
3728
- // CHANGE THIS to use metadata but keep clientName and clientVersion compatible
3729
- var dsn = this.getDsn();
3730
- var header = ["Sentry sentry_version=" + SENTRY_API_VERSION];
3731
- header.push("sentry_client=" + clientName + "/" + clientVersion);
3732
- header.push("sentry_key=" + dsn.publicKey);
3733
- if (dsn.pass) {
3734
- header.push("sentry_secret=" + dsn.pass);
3735
- }
3736
- return {
3737
- 'Content-Type': 'application/json',
3738
- 'X-Sentry-Auth': header.join(', '),
3739
- };
3740
- };
3741
- /** Returns the url to the report dialog endpoint. */
3742
- API.prototype.getReportDialogEndpoint = function (dialogOptions) {
3743
- if (dialogOptions === void 0) { dialogOptions = {}; }
3744
- var dsn = this.getDsn();
3745
- var endpoint = this.getBaseApiEndpoint() + "embed/error-page/";
3746
- var encodedOptions = [];
3747
- encodedOptions.push("dsn=" + dsn.toString());
3748
- for (var key in dialogOptions) {
3749
- if (key === 'dsn') {
3590
+ }
3591
+ /** Returns the prefix to construct Sentry ingestion API endpoints. */
3592
+ function getBaseApiEndpoint(dsn) {
3593
+ var protocol = dsn.protocol ? dsn.protocol + ":" : '';
3594
+ var port = dsn.port ? ":" + dsn.port : '';
3595
+ return protocol + "//" + dsn.host + port + (dsn.path ? "/" + dsn.path : '') + "/api/";
3596
+ }
3597
+ /** Returns the ingest API endpoint for target. */
3598
+ function _getIngestEndpoint(dsn, target) {
3599
+ return "" + getBaseApiEndpoint(dsn) + dsn.projectId + "/" + target + "/";
3600
+ }
3601
+ /** Returns a URL-encoded string with auth config suitable for a query string. */
3602
+ function _encodedAuth(dsn) {
3603
+ return urlEncode({
3604
+ // We send only the minimum set of required information. See
3605
+ // https://github.com/getsentry/sentry-javascript/issues/2572.
3606
+ sentry_key: dsn.publicKey,
3607
+ sentry_version: SENTRY_API_VERSION,
3608
+ });
3609
+ }
3610
+ /** Returns the store endpoint URL. */
3611
+ function getStoreEndpoint(dsn) {
3612
+ return _getIngestEndpoint(dsn, 'store');
3613
+ }
3614
+ /**
3615
+ * Returns the store endpoint URL with auth in the query string.
3616
+ *
3617
+ * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.
3618
+ */
3619
+ function getStoreEndpointWithUrlEncodedAuth(dsn) {
3620
+ return getStoreEndpoint(dsn) + "?" + _encodedAuth(dsn);
3621
+ }
3622
+ /** Returns the envelope endpoint URL. */
3623
+ function _getEnvelopeEndpoint(dsn) {
3624
+ return _getIngestEndpoint(dsn, 'envelope');
3625
+ }
3626
+ /**
3627
+ * Returns the envelope endpoint URL with auth in the query string.
3628
+ *
3629
+ * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.
3630
+ */
3631
+ function getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel) {
3632
+ return tunnel ? tunnel : _getEnvelopeEndpoint(dsn) + "?" + _encodedAuth(dsn);
3633
+ }
3634
+ /** Returns the url to the report dialog endpoint. */
3635
+ function getReportDialogEndpoint(dsnLike, dialogOptions) {
3636
+ var dsn = makeDsn(dsnLike);
3637
+ var endpoint = getBaseApiEndpoint(dsn) + "embed/error-page/";
3638
+ var encodedOptions = "dsn=" + dsnToString(dsn);
3639
+ for (var key in dialogOptions) {
3640
+ if (key === 'dsn') {
3641
+ continue;
3642
+ }
3643
+ if (key === 'user') {
3644
+ if (!dialogOptions.user) {
3750
3645
  continue;
3751
3646
  }
3752
- if (key === 'user') {
3753
- if (!dialogOptions.user) {
3754
- continue;
3755
- }
3756
- if (dialogOptions.user.name) {
3757
- encodedOptions.push("name=" + encodeURIComponent(dialogOptions.user.name));
3758
- }
3759
- if (dialogOptions.user.email) {
3760
- encodedOptions.push("email=" + encodeURIComponent(dialogOptions.user.email));
3761
- }
3647
+ if (dialogOptions.user.name) {
3648
+ encodedOptions += "&name=" + encodeURIComponent(dialogOptions.user.name);
3762
3649
  }
3763
- else {
3764
- encodedOptions.push(encodeURIComponent(key) + "=" + encodeURIComponent(dialogOptions[key]));
3650
+ if (dialogOptions.user.email) {
3651
+ encodedOptions += "&email=" + encodeURIComponent(dialogOptions.user.email);
3765
3652
  }
3766
3653
  }
3767
- if (encodedOptions.length) {
3768
- return endpoint + "?" + encodedOptions.join('&');
3769
- }
3770
- return endpoint;
3771
- };
3772
- /** Returns the envelope endpoint URL. */
3773
- API.prototype._getEnvelopeEndpoint = function () {
3774
- return this._getIngestEndpoint('envelope');
3775
- };
3776
- /** Returns the ingest API endpoint for target. */
3777
- API.prototype._getIngestEndpoint = function (target) {
3778
- if (this._tunnel) {
3779
- return this._tunnel;
3654
+ else {
3655
+ encodedOptions += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(dialogOptions[key]);
3780
3656
  }
3781
- var base = this.getBaseApiEndpoint();
3782
- var dsn = this.getDsn();
3783
- return "" + base + dsn.projectId + "/" + target + "/";
3784
- };
3785
- /** Returns a URL-encoded string with auth config suitable for a query string. */
3786
- API.prototype._encodedAuth = function () {
3787
- var dsn = this.getDsn();
3788
- var auth = {
3789
- // We send only the minimum set of required information. See
3790
- // https://github.com/getsentry/sentry-javascript/issues/2572.
3791
- sentry_key: dsn.publicKey,
3792
- sentry_version: SENTRY_API_VERSION,
3793
- };
3794
- return urlEncode(auth);
3795
- };
3796
- return API;
3797
- }());
3657
+ }
3658
+ return endpoint + "?" + encodedOptions;
3659
+ }
3798
3660
 
3799
3661
  var installedIntegrations = [];
3800
3662
  /**
@@ -3855,7 +3717,7 @@ var Sentry = (function (exports) {
3855
3717
  // set the `initialized` flag so we don't run through the process again unecessarily; use `Object.defineProperty`
3856
3718
  // because by default it creates a property which is nonenumerable, which we want since `initialized` shouldn't be
3857
3719
  // considered a member of the index the way the actual integrations are
3858
- Object.defineProperty(integrations, 'initialized', { value: true });
3720
+ addNonEnumerableProperty(integrations, 'initialized', true);
3859
3721
  return integrations;
3860
3722
  }
3861
3723
 
@@ -3907,7 +3769,7 @@ var Sentry = (function (exports) {
3907
3769
  this._backend = new backendClass(options);
3908
3770
  this._options = options;
3909
3771
  if (options.dsn) {
3910
- this._dsn = new Dsn(options.dsn);
3772
+ this._dsn = makeDsn(options.dsn);
3911
3773
  }
3912
3774
  }
3913
3775
  /**
@@ -3950,9 +3812,8 @@ var Sentry = (function (exports) {
3950
3812
  * @inheritDoc
3951
3813
  */
3952
3814
  BaseClient.prototype.captureEvent = function (event, hint, scope) {
3953
- var _a;
3954
3815
  // ensure we haven't captured this very object before
3955
- if (((_a = hint) === null || _a === void 0 ? void 0 : _a.originalException) && checkOrSetAlreadyCaught(hint.originalException)) {
3816
+ if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {
3956
3817
  logger.log(ALREADY_SEEN_ERROR);
3957
3818
  return;
3958
3819
  }
@@ -3967,11 +3828,15 @@ var Sentry = (function (exports) {
3967
3828
  */
3968
3829
  BaseClient.prototype.captureSession = function (session) {
3969
3830
  if (!this._isEnabled()) {
3970
- logger.warn('SDK not enabled, will not capture session.');
3831
+ if (isDebugBuild()) {
3832
+ logger.warn('SDK not enabled, will not capture session.');
3833
+ }
3971
3834
  return;
3972
3835
  }
3973
3836
  if (!(typeof session.release === 'string')) {
3974
- logger.warn('Discarded session because of missing or non-string release');
3837
+ if (isDebugBuild()) {
3838
+ logger.warn('Discarded session because of missing or non-string release');
3839
+ }
3975
3840
  }
3976
3841
  else {
3977
3842
  this._sendSession(session);
@@ -4067,10 +3932,10 @@ var Sentry = (function (exports) {
4067
3932
  // A session is updated and that session update is sent in only one of the two following scenarios:
4068
3933
  // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update
4069
3934
  // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update
4070
- var sessionNonTerminal = session.status === SessionStatus.Ok;
3935
+ var sessionNonTerminal = session.status === 'ok';
4071
3936
  var shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);
4072
3937
  if (shouldUpdateAndSend) {
4073
- session.update(__assign(__assign({}, (crashed && { status: SessionStatus.Crashed })), { errors: session.errors || Number(errored || crashed) }));
3938
+ session.update(__assign(__assign({}, (crashed && { status: 'crashed' })), { errors: session.errors || Number(errored || crashed) }));
4074
3939
  this.captureSession(session);
4075
3940
  }
4076
3941
  };
@@ -4143,7 +4008,7 @@ var Sentry = (function (exports) {
4143
4008
  finalScope = Scope.clone(finalScope).update(hint.captureContext);
4144
4009
  }
4145
4010
  // We prepare the result here with a resolved Event.
4146
- var result = SyncPromise.resolve(prepared);
4011
+ var result = resolvedSyncPromise(prepared);
4147
4012
  // This should be the last thing called, since we want that
4148
4013
  // {@link Hub.addEventProcessor} gets the finished prepared event.
4149
4014
  if (finalScope) {
@@ -4193,10 +4058,7 @@ var Sentry = (function (exports) {
4193
4058
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
4194
4059
  normalized.contexts.trace = event.contexts.trace;
4195
4060
  }
4196
- var _a = this.getOptions()._experiments, _experiments = _a === void 0 ? {} : _a;
4197
- if (_experiments.ensureNoCircularStructures) {
4198
- return normalize(normalized);
4199
- }
4061
+ event.sdkProcessingMetadata = __assign(__assign({}, event.sdkProcessingMetadata), { baseClientNormalized: true });
4200
4062
  return normalized;
4201
4063
  };
4202
4064
  /**
@@ -4276,26 +4138,29 @@ var Sentry = (function (exports) {
4276
4138
  */
4277
4139
  BaseClient.prototype._processEvent = function (event, hint, scope) {
4278
4140
  var _this = this;
4279
- var _a, _b;
4280
4141
  // eslint-disable-next-line @typescript-eslint/unbound-method
4281
- var _c = this.getOptions(), beforeSend = _c.beforeSend, sampleRate = _c.sampleRate;
4142
+ var _a = this.getOptions(), beforeSend = _a.beforeSend, sampleRate = _a.sampleRate;
4282
4143
  var transport = this.getTransport();
4144
+ function recordLostEvent(outcome, category) {
4145
+ if (transport.recordLostEvent) {
4146
+ transport.recordLostEvent(outcome, category);
4147
+ }
4148
+ }
4283
4149
  if (!this._isEnabled()) {
4284
- return SyncPromise.reject(new SentryError('SDK not enabled, will not capture event.'));
4150
+ return rejectedSyncPromise(new SentryError('SDK not enabled, will not capture event.'));
4285
4151
  }
4286
4152
  var isTransaction = event.type === 'transaction';
4287
4153
  // 1.0 === 100% events are sent
4288
4154
  // 0.0 === 0% events are sent
4289
4155
  // Sampling for transaction happens somewhere else
4290
4156
  if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) {
4291
- (_b = (_a = transport).recordLostEvent) === null || _b === void 0 ? void 0 : _b.call(_a, Outcome.SampleRate, 'event');
4292
- return SyncPromise.reject(new SentryError("Discarding event because it's not included in the random sample (sampling rate = " + sampleRate + ")"));
4157
+ recordLostEvent('sample_rate', 'event');
4158
+ return rejectedSyncPromise(new SentryError("Discarding event because it's not included in the random sample (sampling rate = " + sampleRate + ")"));
4293
4159
  }
4294
4160
  return this._prepareEvent(event, scope, hint)
4295
4161
  .then(function (prepared) {
4296
- var _a, _b;
4297
4162
  if (prepared === null) {
4298
- (_b = (_a = transport).recordLostEvent) === null || _b === void 0 ? void 0 : _b.call(_a, Outcome.EventProcessor, event.type || 'event');
4163
+ recordLostEvent('event_processor', event.type || 'event');
4299
4164
  throw new SentryError('An event processor returned null, will not send event.');
4300
4165
  }
4301
4166
  var isInternalException = hint && hint.data && hint.data.__sentry__ === true;
@@ -4303,12 +4168,11 @@ var Sentry = (function (exports) {
4303
4168
  return prepared;
4304
4169
  }
4305
4170
  var beforeSendResult = beforeSend(prepared, hint);
4306
- return _this._ensureBeforeSendRv(beforeSendResult);
4171
+ return _ensureBeforeSendRv(beforeSendResult);
4307
4172
  })
4308
4173
  .then(function (processedEvent) {
4309
- var _a, _b;
4310
4174
  if (processedEvent === null) {
4311
- (_b = (_a = transport).recordLostEvent) === null || _b === void 0 ? void 0 : _b.call(_a, Outcome.BeforeSend, event.type || 'event');
4175
+ recordLostEvent('before_send', event.type || 'event');
4312
4176
  throw new SentryError('`beforeSend` returned `null`, will not send event.');
4313
4177
  }
4314
4178
  var session = scope && scope.getSession && scope.getSession();
@@ -4345,28 +4209,28 @@ var Sentry = (function (exports) {
4345
4209
  return reason;
4346
4210
  });
4347
4211
  };
4348
- /**
4349
- * Verifies that return value of configured `beforeSend` is of expected type.
4350
- */
4351
- BaseClient.prototype._ensureBeforeSendRv = function (rv) {
4352
- var nullErr = '`beforeSend` method has to return `null` or a valid event.';
4353
- if (isThenable(rv)) {
4354
- return rv.then(function (event) {
4355
- if (!(isPlainObject(event) || event === null)) {
4356
- throw new SentryError(nullErr);
4357
- }
4358
- return event;
4359
- }, function (e) {
4360
- throw new SentryError("beforeSend rejected with " + e);
4361
- });
4362
- }
4363
- else if (!(isPlainObject(rv) || rv === null)) {
4364
- throw new SentryError(nullErr);
4365
- }
4366
- return rv;
4367
- };
4368
4212
  return BaseClient;
4369
- }());
4213
+ }());
4214
+ /**
4215
+ * Verifies that return value of configured `beforeSend` is of expected type.
4216
+ */
4217
+ function _ensureBeforeSendRv(rv) {
4218
+ var nullErr = '`beforeSend` method has to return `null` or a valid event.';
4219
+ if (isThenable(rv)) {
4220
+ return rv.then(function (event) {
4221
+ if (!(isPlainObject(event) || event === null)) {
4222
+ throw new SentryError(nullErr);
4223
+ }
4224
+ return event;
4225
+ }, function (e) {
4226
+ throw new SentryError("beforeSend rejected with " + e);
4227
+ });
4228
+ }
4229
+ else if (!(isPlainObject(rv) || rv === null)) {
4230
+ throw new SentryError(nullErr);
4231
+ }
4232
+ return rv;
4233
+ }
4370
4234
 
4371
4235
  /** Noop transport */
4372
4236
  var NoopTransport = /** @class */ (function () {
@@ -4376,16 +4240,16 @@ var Sentry = (function (exports) {
4376
4240
  * @inheritDoc
4377
4241
  */
4378
4242
  NoopTransport.prototype.sendEvent = function (_) {
4379
- return SyncPromise.resolve({
4243
+ return resolvedSyncPromise({
4380
4244
  reason: "NoopTransport: Event has been skipped because no Dsn is configured.",
4381
- status: exports.Status.Skipped,
4245
+ status: 'skipped',
4382
4246
  });
4383
4247
  };
4384
4248
  /**
4385
4249
  * @inheritDoc
4386
4250
  */
4387
4251
  NoopTransport.prototype.close = function (_) {
4388
- return SyncPromise.resolve(true);
4252
+ return resolvedSyncPromise(true);
4389
4253
  };
4390
4254
  return NoopTransport;
4391
4255
  }());
@@ -4421,7 +4285,9 @@ var Sentry = (function (exports) {
4421
4285
  */
4422
4286
  BaseBackend.prototype.sendEvent = function (event) {
4423
4287
  void this._transport.sendEvent(event).then(null, function (reason) {
4424
- logger.error("Error while sending event: " + reason);
4288
+ if (isDebugBuild()) {
4289
+ logger.error("Error while sending event: " + reason);
4290
+ }
4425
4291
  });
4426
4292
  };
4427
4293
  /**
@@ -4429,11 +4295,15 @@ var Sentry = (function (exports) {
4429
4295
  */
4430
4296
  BaseBackend.prototype.sendSession = function (session) {
4431
4297
  if (!this._transport.sendSession) {
4432
- logger.warn("Dropping session because custom transport doesn't implement sendSession");
4298
+ if (isDebugBuild()) {
4299
+ logger.warn("Dropping session because custom transport doesn't implement sendSession");
4300
+ }
4433
4301
  return;
4434
4302
  }
4435
4303
  void this._transport.sendSession(session).then(null, function (reason) {
4436
- logger.error("Error while sending session: " + reason);
4304
+ if (isDebugBuild()) {
4305
+ logger.error("Error while sending session: " + reason);
4306
+ }
4437
4307
  });
4438
4308
  };
4439
4309
  /**
@@ -4477,7 +4347,7 @@ var Sentry = (function (exports) {
4477
4347
  /** Creates a SentryRequest from a Session. */
4478
4348
  function sessionToSentryRequest(session, api) {
4479
4349
  var sdkInfo = getSdkMetadataForEnvelopeHeader(api);
4480
- var envelopeHeaders = JSON.stringify(__assign(__assign({ sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (api.forceEnvelope() && { dsn: api.getDsn().toString() })));
4350
+ var envelopeHeaders = JSON.stringify(__assign(__assign({ sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (!!api.tunnel && { dsn: dsnToString(api.dsn) })));
4481
4351
  // I know this is hacky but we don't want to add `session` to request type since it's never rate limited
4482
4352
  var type = 'aggregates' in session ? 'sessions' : 'session';
4483
4353
  var itemHeaders = JSON.stringify({
@@ -4486,26 +4356,70 @@ var Sentry = (function (exports) {
4486
4356
  return {
4487
4357
  body: envelopeHeaders + "\n" + itemHeaders + "\n" + JSON.stringify(session),
4488
4358
  type: type,
4489
- url: api.getEnvelopeEndpointWithUrlEncodedAuth(),
4359
+ url: getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel),
4490
4360
  };
4491
4361
  }
4492
4362
  /** Creates a SentryRequest from an event. */
4493
4363
  function eventToSentryRequest(event, api) {
4494
4364
  var sdkInfo = getSdkMetadataForEnvelopeHeader(api);
4495
4365
  var eventType = event.type || 'event';
4496
- var useEnvelope = eventType === 'transaction' || api.forceEnvelope();
4497
- var _a = event.debug_meta || {}, transactionSampling = _a.transactionSampling, metadata = __rest(_a, ["transactionSampling"]);
4498
- var _b = transactionSampling || {}, samplingMethod = _b.method, sampleRate = _b.rate;
4499
- if (Object.keys(metadata).length === 0) {
4500
- delete event.debug_meta;
4366
+ var useEnvelope = eventType === 'transaction' || !!api.tunnel;
4367
+ var transactionSampling = (event.sdkProcessingMetadata || {}).transactionSampling;
4368
+ var _a = transactionSampling || {}, samplingMethod = _a.method, sampleRate = _a.rate;
4369
+ // TODO: Below is a temporary hack in order to debug a serialization error - see
4370
+ // https://github.com/getsentry/sentry-javascript/issues/2809 and
4371
+ // https://github.com/getsentry/sentry-javascript/pull/4425. TL;DR: even though we normalize all events (which should
4372
+ // prevent this), something is causing `JSON.stringify` to throw a circular reference error.
4373
+ //
4374
+ // When it's time to remove it:
4375
+ // 1. Delete everything between here and where the request object `req` is created, EXCEPT the line deleting
4376
+ // `sdkProcessingMetadata`
4377
+ // 2. Restore the original version of the request body, which is commented out
4378
+ // 3. Search for `skippedNormalization` and pull out the companion hack in the browser playwright tests
4379
+ enhanceEventWithSdkInfo(event, api.metadata.sdk);
4380
+ event.tags = event.tags || {};
4381
+ event.extra = event.extra || {};
4382
+ // In theory, all events should be marked as having gone through normalization and so
4383
+ // we should never set this tag
4384
+ if (!(event.sdkProcessingMetadata && event.sdkProcessingMetadata.baseClientNormalized)) {
4385
+ event.tags.skippedNormalization = true;
4386
+ }
4387
+ // prevent this data from being sent to sentry
4388
+ // TODO: This is NOT part of the hack - DO NOT DELETE
4389
+ delete event.sdkProcessingMetadata;
4390
+ var body;
4391
+ try {
4392
+ // 99.9% of events should get through just fine - no change in behavior for them
4393
+ body = JSON.stringify(event);
4501
4394
  }
4502
- else {
4503
- event.debug_meta = metadata;
4395
+ catch (err) {
4396
+ // Record data about the error without replacing original event data, then force renormalization
4397
+ event.tags.JSONStringifyError = true;
4398
+ event.extra.JSONStringifyError = err;
4399
+ try {
4400
+ body = JSON.stringify(normalize(event));
4401
+ }
4402
+ catch (newErr) {
4403
+ // At this point even renormalization hasn't worked, meaning something about the event data has gone very wrong.
4404
+ // Time to cut our losses and record only the new error. With luck, even in the problematic cases we're trying to
4405
+ // debug with this hack, we won't ever land here.
4406
+ var innerErr = newErr;
4407
+ body = JSON.stringify({
4408
+ message: 'JSON.stringify error after renormalization',
4409
+ // setting `extra: { innerErr }` here for some reason results in an empty object, so unpack manually
4410
+ extra: { message: innerErr.message, stack: innerErr.stack },
4411
+ });
4412
+ }
4504
4413
  }
4505
4414
  var req = {
4506
- body: JSON.stringify(sdkInfo ? enhanceEventWithSdkInfo(event, api.metadata.sdk) : event),
4415
+ // this is the relevant line of code before the hack was added, to make it easy to undo said hack once we've solved
4416
+ // the mystery
4417
+ // body: JSON.stringify(sdkInfo ? enhanceEventWithSdkInfo(event, api.metadata.sdk) : event),
4418
+ body: body,
4507
4419
  type: eventType,
4508
- url: useEnvelope ? api.getEnvelopeEndpointWithUrlEncodedAuth() : api.getStoreEndpointWithUrlEncodedAuth(),
4420
+ url: useEnvelope
4421
+ ? getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel)
4422
+ : getStoreEndpointWithUrlEncodedAuth(api.dsn),
4509
4423
  };
4510
4424
  // https://develop.sentry.dev/sdk/envelopes/
4511
4425
  // Since we don't need to manipulate envelopes nor store them, there is no
@@ -4513,7 +4427,7 @@ var Sentry = (function (exports) {
4513
4427
  // deserialization. Instead, we only implement a minimal subset of the spec to
4514
4428
  // serialize events inline here.
4515
4429
  if (useEnvelope) {
4516
- var envelopeHeaders = JSON.stringify(__assign(__assign({ event_id: event.event_id, sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (api.forceEnvelope() && { dsn: api.getDsn().toString() })));
4430
+ var envelopeHeaders = JSON.stringify(__assign(__assign({ event_id: event.event_id, sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (!!api.tunnel && { dsn: dsnToString(api.dsn) })));
4517
4431
  var itemHeaders = JSON.stringify({
4518
4432
  type: eventType,
4519
4433
  // TODO: Right now, sampleRate may or may not be defined (it won't be in the cases of inheritance and
@@ -4538,17 +4452,19 @@ var Sentry = (function (exports) {
4538
4452
  * @param options Options to pass to the client.
4539
4453
  */
4540
4454
  function initAndBind(clientClass, options) {
4541
- var _a;
4542
4455
  if (options.debug === true) {
4543
4456
  logger.enable();
4544
4457
  }
4545
4458
  var hub = getCurrentHub();
4546
- (_a = hub.getScope()) === null || _a === void 0 ? void 0 : _a.update(options.initialScope);
4459
+ var scope = hub.getScope();
4460
+ if (scope) {
4461
+ scope.update(options.initialScope);
4462
+ }
4547
4463
  var client = new clientClass(options);
4548
4464
  hub.bindClient(client);
4549
4465
  }
4550
4466
 
4551
- var SDK_VERSION = '6.16.1';
4467
+ var SDK_VERSION = '6.17.2';
4552
4468
 
4553
4469
  var originalFunctionToString;
4554
4470
  /** Patch toString calls to return proper name for wrapped functions */
@@ -4571,7 +4487,7 @@ var Sentry = (function (exports) {
4571
4487
  for (var _i = 0; _i < arguments.length; _i++) {
4572
4488
  args[_i] = arguments[_i];
4573
4489
  }
4574
- var context = this.__sentry_original__ || this;
4490
+ var context = getOriginalFunction(this) || this;
4575
4491
  return originalFunctionToString.apply(context, args);
4576
4492
  };
4577
4493
  };
@@ -4625,19 +4541,27 @@ var Sentry = (function (exports) {
4625
4541
  /** JSDoc */
4626
4542
  InboundFilters.prototype._shouldDropEvent = function (event, options) {
4627
4543
  if (this._isSentryError(event, options)) {
4628
- logger.warn("Event dropped due to being internal Sentry Error.\nEvent: " + getEventDescription(event));
4544
+ if (isDebugBuild()) {
4545
+ logger.warn("Event dropped due to being internal Sentry Error.\nEvent: " + getEventDescription(event));
4546
+ }
4629
4547
  return true;
4630
4548
  }
4631
4549
  if (this._isIgnoredError(event, options)) {
4632
- logger.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: " + getEventDescription(event));
4550
+ if (isDebugBuild()) {
4551
+ logger.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: " + getEventDescription(event));
4552
+ }
4633
4553
  return true;
4634
4554
  }
4635
4555
  if (this._isDeniedUrl(event, options)) {
4636
- logger.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: " + getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event));
4556
+ if (isDebugBuild()) {
4557
+ logger.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: " + getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event));
4558
+ }
4637
4559
  return true;
4638
4560
  }
4639
4561
  if (!this._isAllowedUrl(event, options)) {
4640
- logger.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: " + getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event));
4562
+ if (isDebugBuild()) {
4563
+ logger.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: " + getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event));
4564
+ }
4641
4565
  return true;
4642
4566
  }
4643
4567
  return false;
@@ -4648,16 +4572,14 @@ var Sentry = (function (exports) {
4648
4572
  return false;
4649
4573
  }
4650
4574
  try {
4651
- return ((event &&
4652
- event.exception &&
4653
- event.exception.values &&
4654
- event.exception.values[0] &&
4655
- event.exception.values[0].type === 'SentryError') ||
4656
- false);
4575
+ // @ts-ignore can't be a sentry error if undefined
4576
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
4577
+ return event.exception.values[0].type === 'SentryError';
4657
4578
  }
4658
- catch (_oO) {
4659
- return false;
4579
+ catch (e) {
4580
+ // ignore
4660
4581
  }
4582
+ return false;
4661
4583
  };
4662
4584
  /** JSDoc */
4663
4585
  InboundFilters.prototype._isIgnoredError = function (event, options) {
@@ -4708,7 +4630,9 @@ var Sentry = (function (exports) {
4708
4630
  return ["" + value, type + ": " + value];
4709
4631
  }
4710
4632
  catch (oO) {
4711
- logger.error("Cannot extract message for event " + getEventDescription(event));
4633
+ if (isDebugBuild()) {
4634
+ logger.error("Cannot extract message for event " + getEventDescription(event));
4635
+ }
4712
4636
  return [];
4713
4637
  }
4714
4638
  }
@@ -4717,10 +4641,9 @@ var Sentry = (function (exports) {
4717
4641
  /** JSDoc */
4718
4642
  InboundFilters.prototype._getLastValidUrl = function (frames) {
4719
4643
  if (frames === void 0) { frames = []; }
4720
- var _a, _b;
4721
4644
  for (var i = frames.length - 1; i >= 0; i--) {
4722
4645
  var frame = frames[i];
4723
- if (((_a = frame) === null || _a === void 0 ? void 0 : _a.filename) !== '<anonymous>' && ((_b = frame) === null || _b === void 0 ? void 0 : _b.filename) !== '[native code]') {
4646
+ if (frame && frame.filename !== '<anonymous>' && frame.filename !== '[native code]') {
4724
4647
  return frame.filename || null;
4725
4648
  }
4726
4649
  }
@@ -4730,17 +4653,22 @@ var Sentry = (function (exports) {
4730
4653
  InboundFilters.prototype._getEventFilterUrl = function (event) {
4731
4654
  try {
4732
4655
  if (event.stacktrace) {
4733
- var frames_1 = event.stacktrace.frames;
4734
- return this._getLastValidUrl(frames_1);
4656
+ return this._getLastValidUrl(event.stacktrace.frames);
4735
4657
  }
4736
- if (event.exception) {
4737
- var frames_2 = event.exception.values && event.exception.values[0].stacktrace && event.exception.values[0].stacktrace.frames;
4738
- return this._getLastValidUrl(frames_2);
4658
+ var frames_1;
4659
+ try {
4660
+ // @ts-ignore we only care about frames if the whole thing here is defined
4661
+ frames_1 = event.exception.values[0].stacktrace.frames;
4739
4662
  }
4740
- return null;
4663
+ catch (e) {
4664
+ // ignore
4665
+ }
4666
+ return frames_1 ? this._getLastValidUrl(frames_1) : null;
4741
4667
  }
4742
4668
  catch (oO) {
4743
- logger.error("Cannot extract url for event " + getEventDescription(event));
4669
+ if (isDebugBuild()) {
4670
+ logger.error("Cannot extract url for event " + getEventDescription(event));
4671
+ }
4744
4672
  return null;
4745
4673
  }
4746
4674
  };
@@ -5104,7 +5032,7 @@ var Sentry = (function (exports) {
5104
5032
  }
5105
5033
 
5106
5034
  /**
5107
- * Builds and Event from a Exception
5035
+ * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.
5108
5036
  * @hidden
5109
5037
  */
5110
5038
  function eventFromException(options, exception, hint) {
@@ -5117,7 +5045,7 @@ var Sentry = (function (exports) {
5117
5045
  if (hint && hint.event_id) {
5118
5046
  event.event_id = hint.event_id;
5119
5047
  }
5120
- return SyncPromise.resolve(event);
5048
+ return resolvedSyncPromise(event);
5121
5049
  }
5122
5050
  /**
5123
5051
  * Builds and Event from a Message
@@ -5133,7 +5061,7 @@ var Sentry = (function (exports) {
5133
5061
  if (hint && hint.event_id) {
5134
5062
  event.event_id = hint.event_id;
5135
5063
  }
5136
- return SyncPromise.resolve(event);
5064
+ return resolvedSyncPromise(event);
5137
5065
  }
5138
5066
  /**
5139
5067
  * @hidden
@@ -5178,11 +5106,11 @@ var Sentry = (function (exports) {
5178
5106
  return event;
5179
5107
  }
5180
5108
  if (isPlainObject(exception) || isEvent(exception)) {
5181
- // If it is plain Object or Event, serialize it manually and extract options
5182
- // This will allow us to group events based on top-level keys
5183
- // which is much better than creating new group when any key/value change
5109
+ // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize
5110
+ // it manually. This will allow us to group events based on top-level keys which is much better than creating a new
5111
+ // group on any key/value change.
5184
5112
  var objectException = exception;
5185
- event = eventFromPlainObject(objectException, syntheticException, options.rejection);
5113
+ event = eventFromPlainObject(objectException, syntheticException, options.isRejection);
5186
5114
  addExceptionMechanism(event, {
5187
5115
  synthetic: true,
5188
5116
  });
@@ -5263,7 +5191,6 @@ var Sentry = (function (exports) {
5263
5191
  * Safari: resource blocked by content blocker
5264
5192
  */
5265
5193
  function getNativeFetchImplementation() {
5266
- var _a, _b;
5267
5194
  if (cachedFetchImpl) {
5268
5195
  return cachedFetchImpl;
5269
5196
  }
@@ -5275,18 +5202,21 @@ var Sentry = (function (exports) {
5275
5202
  var document = global$3.document;
5276
5203
  var fetchImpl = global$3.fetch;
5277
5204
  // eslint-disable-next-line deprecation/deprecation
5278
- if (typeof ((_a = document) === null || _a === void 0 ? void 0 : _a.createElement) === "function") {
5205
+ if (document && typeof document.createElement === "function") {
5279
5206
  try {
5280
5207
  var sandbox = document.createElement('iframe');
5281
5208
  sandbox.hidden = true;
5282
5209
  document.head.appendChild(sandbox);
5283
- if ((_b = sandbox.contentWindow) === null || _b === void 0 ? void 0 : _b.fetch) {
5284
- fetchImpl = sandbox.contentWindow.fetch;
5210
+ var contentWindow = sandbox.contentWindow;
5211
+ if (contentWindow && contentWindow.fetch) {
5212
+ fetchImpl = contentWindow.fetch;
5285
5213
  }
5286
5214
  document.head.removeChild(sandbox);
5287
5215
  }
5288
5216
  catch (e) {
5289
- logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);
5217
+ if (isDebugBuild()) {
5218
+ logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);
5219
+ }
5290
5220
  }
5291
5221
  }
5292
5222
  return (cachedFetchImpl = fetchImpl.bind(global$3));
@@ -5317,12 +5247,10 @@ var Sentry = (function (exports) {
5317
5247
  }
5318
5248
  }
5319
5249
 
5320
- var CATEGORY_MAPPING = {
5321
- event: 'error',
5322
- transaction: 'transaction',
5323
- session: 'session',
5324
- attachment: 'attachment',
5325
- };
5250
+ function requestTypeToCategory(ty) {
5251
+ var tyStr = ty;
5252
+ return tyStr === 'event' ? 'error' : tyStr;
5253
+ }
5326
5254
  var global$4 = getGlobalObject();
5327
5255
  /** Base Transport class implementation */
5328
5256
  var BaseTransport = /** @class */ (function () {
@@ -5330,13 +5258,13 @@ var Sentry = (function (exports) {
5330
5258
  var _this = this;
5331
5259
  this.options = options;
5332
5260
  /** A simple buffer holding all requests. */
5333
- this._buffer = new PromiseBuffer(30);
5261
+ this._buffer = makePromiseBuffer(30);
5334
5262
  /** Locks transport after receiving rate limits in a response */
5335
5263
  this._rateLimits = {};
5336
5264
  this._outcomes = {};
5337
- this._api = new API(options.dsn, options._metadata, options.tunnel);
5265
+ this._api = initAPIDetails(options.dsn, options._metadata, options.tunnel);
5338
5266
  // eslint-disable-next-line deprecation/deprecation
5339
- this.url = this._api.getStoreEndpointWithUrlEncodedAuth();
5267
+ this.url = getStoreEndpointWithUrlEncodedAuth(this._api.dsn);
5340
5268
  if (this.options.sendClientReports && global$4.document) {
5341
5269
  global$4.document.addEventListener('visibilitychange', function () {
5342
5270
  if (global$4.document.visibilityState === 'hidden') {
@@ -5348,8 +5276,14 @@ var Sentry = (function (exports) {
5348
5276
  /**
5349
5277
  * @inheritDoc
5350
5278
  */
5351
- BaseTransport.prototype.sendEvent = function (_) {
5352
- throw new SentryError('Transport Class has to implement `sendEvent` method');
5279
+ BaseTransport.prototype.sendEvent = function (event) {
5280
+ return this._sendRequest(eventToSentryRequest(event, this._api), event);
5281
+ };
5282
+ /**
5283
+ * @inheritDoc
5284
+ */
5285
+ BaseTransport.prototype.sendSession = function (session) {
5286
+ return this._sendRequest(sessionToSentryRequest(session, this._api), session);
5353
5287
  };
5354
5288
  /**
5355
5289
  * @inheritDoc
@@ -5370,7 +5304,7 @@ var Sentry = (function (exports) {
5370
5304
  // We could use nested maps, but it's much easier to read and type this way.
5371
5305
  // A correct type for map-based implementation if we want to go that route
5372
5306
  // would be `Partial<Record<SentryRequestType, Partial<Record<Outcome, number>>>>`
5373
- var key = CATEGORY_MAPPING[category] + ":" + reason;
5307
+ var key = requestTypeToCategory(category) + ":" + reason;
5374
5308
  logger.log("Adding outcome: " + key);
5375
5309
  this._outcomes[key] = (_a = this._outcomes[key], (_a !== null && _a !== void 0 ? _a : 0)) + 1;
5376
5310
  };
@@ -5389,9 +5323,9 @@ var Sentry = (function (exports) {
5389
5323
  return;
5390
5324
  }
5391
5325
  logger.log("Flushing outcomes:\n" + JSON.stringify(outcomes, null, 2));
5392
- var url = this._api.getEnvelopeEndpointWithUrlEncodedAuth();
5326
+ var url = getEnvelopeEndpointWithUrlEncodedAuth(this._api.dsn, this._api.tunnel);
5393
5327
  // Envelope header is required to be at least an empty object
5394
- var envelopeHeader = JSON.stringify(__assign({}, (this.options.tunnel && { dsn: this._api.getDsn().toString() })));
5328
+ var envelopeHeader = JSON.stringify(__assign({}, (this._api.tunnel && { dsn: dsnToString(this._api.dsn) })));
5395
5329
  var itemHeaders = JSON.stringify({
5396
5330
  type: 'client_report',
5397
5331
  });
@@ -5419,15 +5353,16 @@ var Sentry = (function (exports) {
5419
5353
  */
5420
5354
  BaseTransport.prototype._handleResponse = function (_a) {
5421
5355
  var requestType = _a.requestType, response = _a.response, headers = _a.headers, resolve = _a.resolve, reject = _a.reject;
5422
- var status = exports.Status.fromHttpCode(response.status);
5356
+ var status = eventStatusFromHttpCode(response.status);
5423
5357
  /**
5424
5358
  * "The name is case-insensitive."
5425
5359
  * https://developer.mozilla.org/en-US/docs/Web/API/Headers/get
5426
5360
  */
5427
5361
  var limited = this._handleRateLimit(headers);
5428
- if (limited)
5362
+ if (limited && isDebugBuild()) {
5429
5363
  logger.warn("Too many " + requestType + " requests, backing off until: " + this._disabledUntil(requestType));
5430
- if (status === exports.Status.Success) {
5364
+ }
5365
+ if (status === 'success') {
5431
5366
  resolve({ status: status });
5432
5367
  return;
5433
5368
  }
@@ -5437,7 +5372,7 @@ var Sentry = (function (exports) {
5437
5372
  * Gets the time that given category is disabled until for rate limiting
5438
5373
  */
5439
5374
  BaseTransport.prototype._disabledUntil = function (requestType) {
5440
- var category = CATEGORY_MAPPING[requestType];
5375
+ var category = requestTypeToCategory(requestType);
5441
5376
  return this._rateLimits[category] || this._rateLimits.all;
5442
5377
  };
5443
5378
  /**
@@ -5513,18 +5448,6 @@ var Sentry = (function (exports) {
5513
5448
  _this._fetch = fetchImpl;
5514
5449
  return _this;
5515
5450
  }
5516
- /**
5517
- * @inheritDoc
5518
- */
5519
- FetchTransport.prototype.sendEvent = function (event) {
5520
- return this._sendRequest(eventToSentryRequest(event, this._api), event);
5521
- };
5522
- /**
5523
- * @inheritDoc
5524
- */
5525
- FetchTransport.prototype.sendSession = function (session) {
5526
- return this._sendRequest(sessionToSentryRequest(session, this._api), session);
5527
- };
5528
5451
  /**
5529
5452
  * @param sentryRequest Prepared SentryRequest to be delivered
5530
5453
  * @param originalPayload Original payload used to create SentryRequest
@@ -5532,7 +5455,7 @@ var Sentry = (function (exports) {
5532
5455
  FetchTransport.prototype._sendRequest = function (sentryRequest, originalPayload) {
5533
5456
  var _this = this;
5534
5457
  if (this._isRateLimited(sentryRequest.type)) {
5535
- this.recordLostEvent(Outcome.RateLimitBackoff, sentryRequest.type);
5458
+ this.recordLostEvent('ratelimit_backoff', sentryRequest.type);
5536
5459
  return Promise.reject({
5537
5460
  event: originalPayload,
5538
5461
  type: sentryRequest.type,
@@ -5543,9 +5466,9 @@ var Sentry = (function (exports) {
5543
5466
  var options = {
5544
5467
  body: sentryRequest.body,
5545
5468
  method: 'POST',
5546
- // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default
5547
- // https://caniuse.com/#feat=referrer-policy
5548
- // It doesn't. And it throw exception instead of ignoring this parameter...
5469
+ // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'
5470
+ // (see https://caniuse.com/#feat=referrer-policy),
5471
+ // it doesn't. And it throws an exception instead of ignoring this parameter...
5549
5472
  // REF: https://github.com/getsentry/raven-js/issues/1233
5550
5473
  referrerPolicy: (supportsReferrerPolicy() ? 'origin' : ''),
5551
5474
  };
@@ -5578,10 +5501,10 @@ var Sentry = (function (exports) {
5578
5501
  .then(undefined, function (reason) {
5579
5502
  // It's either buffer rejection or any other xhr/fetch error, which are treated as NetworkError.
5580
5503
  if (reason instanceof SentryError) {
5581
- _this.recordLostEvent(Outcome.QueueOverflow, sentryRequest.type);
5504
+ _this.recordLostEvent('queue_overflow', sentryRequest.type);
5582
5505
  }
5583
5506
  else {
5584
- _this.recordLostEvent(Outcome.NetworkError, sentryRequest.type);
5507
+ _this.recordLostEvent('network_error', sentryRequest.type);
5585
5508
  }
5586
5509
  throw reason;
5587
5510
  });
@@ -5595,18 +5518,6 @@ var Sentry = (function (exports) {
5595
5518
  function XHRTransport() {
5596
5519
  return _super !== null && _super.apply(this, arguments) || this;
5597
5520
  }
5598
- /**
5599
- * @inheritDoc
5600
- */
5601
- XHRTransport.prototype.sendEvent = function (event) {
5602
- return this._sendRequest(eventToSentryRequest(event, this._api), event);
5603
- };
5604
- /**
5605
- * @inheritDoc
5606
- */
5607
- XHRTransport.prototype.sendSession = function (session) {
5608
- return this._sendRequest(sessionToSentryRequest(session, this._api), session);
5609
- };
5610
5521
  /**
5611
5522
  * @param sentryRequest Prepared SentryRequest to be delivered
5612
5523
  * @param originalPayload Original payload used to create SentryRequest
@@ -5614,7 +5525,7 @@ var Sentry = (function (exports) {
5614
5525
  XHRTransport.prototype._sendRequest = function (sentryRequest, originalPayload) {
5615
5526
  var _this = this;
5616
5527
  if (this._isRateLimited(sentryRequest.type)) {
5617
- this.recordLostEvent(Outcome.RateLimitBackoff, sentryRequest.type);
5528
+ this.recordLostEvent('ratelimit_backoff', sentryRequest.type);
5618
5529
  return Promise.reject({
5619
5530
  event: originalPayload,
5620
5531
  type: sentryRequest.type,
@@ -5647,10 +5558,10 @@ var Sentry = (function (exports) {
5647
5558
  .then(undefined, function (reason) {
5648
5559
  // It's either buffer rejection or any other xhr/fetch error, which are treated as NetworkError.
5649
5560
  if (reason instanceof SentryError) {
5650
- _this.recordLostEvent(Outcome.QueueOverflow, sentryRequest.type);
5561
+ _this.recordLostEvent('queue_overflow', sentryRequest.type);
5651
5562
  }
5652
5563
  else {
5653
- _this.recordLostEvent(Outcome.NetworkError, sentryRequest.type);
5564
+ _this.recordLostEvent('network_error', sentryRequest.type);
5654
5565
  }
5655
5566
  throw reason;
5656
5567
  });
@@ -5736,19 +5647,27 @@ var Sentry = (function (exports) {
5736
5647
  * @hidden
5737
5648
  */
5738
5649
  function wrap(fn, options, before) {
5650
+ // for future readers what this does is wrap a function and then create
5651
+ // a bi-directional wrapping between them.
5652
+ //
5653
+ // example: wrapped = wrap(original);
5654
+ // original.__sentry_wrapped__ -> wrapped
5655
+ // wrapped.__sentry_original__ -> original
5739
5656
  if (options === void 0) { options = {}; }
5740
5657
  if (typeof fn !== 'function') {
5741
5658
  return fn;
5742
5659
  }
5743
5660
  try {
5661
+ // if we're dealing with a function that was previously wrapped, return
5662
+ // the original wrapper.
5663
+ var wrapper = fn.__sentry_wrapped__;
5664
+ if (wrapper) {
5665
+ return wrapper;
5666
+ }
5744
5667
  // We don't wanna wrap it twice
5745
- if (fn.__sentry__) {
5668
+ if (getOriginalFunction(fn)) {
5746
5669
  return fn;
5747
5670
  }
5748
- // If this has already been wrapped in the past, return that wrapped function
5749
- if (fn.__sentry_wrapped__) {
5750
- return fn.__sentry_wrapped__;
5751
- }
5752
5671
  }
5753
5672
  catch (e) {
5754
5673
  // Just accessing custom props in some Selenium environments
@@ -5766,14 +5685,6 @@ var Sentry = (function (exports) {
5766
5685
  }
5767
5686
  // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
5768
5687
  var wrappedArguments = args.map(function (arg) { return wrap(arg, options); });
5769
- if (fn.handleEvent) {
5770
- // Attempt to invoke user-land function
5771
- // NOTE: If you are a Sentry user, and you are seeing this stack frame, it
5772
- // means the sentry.javascript SDK caught an error invoking your application code. This
5773
- // is expected behavior and NOT indicative of a bug with sentry.javascript.
5774
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
5775
- return fn.handleEvent.apply(this, wrappedArguments);
5776
- }
5777
5688
  // Attempt to invoke user-land function
5778
5689
  // NOTE: If you are a Sentry user, and you are seeing this stack frame, it
5779
5690
  // means the sentry.javascript SDK caught an error invoking your application code. This
@@ -5784,13 +5695,12 @@ var Sentry = (function (exports) {
5784
5695
  ignoreNextOnError();
5785
5696
  withScope(function (scope) {
5786
5697
  scope.addEventProcessor(function (event) {
5787
- var processedEvent = __assign({}, event);
5788
5698
  if (options.mechanism) {
5789
- addExceptionTypeValue(processedEvent, undefined, undefined);
5790
- addExceptionMechanism(processedEvent, options.mechanism);
5699
+ addExceptionTypeValue(event, undefined, undefined);
5700
+ addExceptionMechanism(event, options.mechanism);
5791
5701
  }
5792
- processedEvent.extra = __assign(__assign({}, processedEvent.extra), { arguments: args });
5793
- return processedEvent;
5702
+ event.extra = __assign(__assign({}, event.extra), { arguments: args });
5703
+ return event;
5794
5704
  });
5795
5705
  captureException(ex);
5796
5706
  });
@@ -5808,24 +5718,10 @@ var Sentry = (function (exports) {
5808
5718
  }
5809
5719
  }
5810
5720
  catch (_oO) { } // eslint-disable-line no-empty
5811
- fn.prototype = fn.prototype || {};
5812
- sentryWrapped.prototype = fn.prototype;
5813
- Object.defineProperty(fn, '__sentry_wrapped__', {
5814
- enumerable: false,
5815
- value: sentryWrapped,
5816
- });
5817
5721
  // Signal that this function has been wrapped/filled already
5818
5722
  // for both debugging and to prevent it to being wrapped/filled twice
5819
- Object.defineProperties(sentryWrapped, {
5820
- __sentry__: {
5821
- enumerable: false,
5822
- value: true,
5823
- },
5824
- __sentry_original__: {
5825
- enumerable: false,
5826
- value: fn,
5827
- },
5828
- });
5723
+ markFunctionWrapped(sentryWrapped, fn);
5724
+ addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);
5829
5725
  // Restore original function name (not all browsers allow that)
5830
5726
  try {
5831
5727
  var descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name');
@@ -5851,16 +5747,20 @@ var Sentry = (function (exports) {
5851
5747
  return;
5852
5748
  }
5853
5749
  if (!options.eventId) {
5854
- logger.error("Missing eventId option in showReportDialog call");
5750
+ if (isDebugBuild()) {
5751
+ logger.error("Missing eventId option in showReportDialog call");
5752
+ }
5855
5753
  return;
5856
5754
  }
5857
5755
  if (!options.dsn) {
5858
- logger.error("Missing dsn option in showReportDialog call");
5756
+ if (isDebugBuild()) {
5757
+ logger.error("Missing dsn option in showReportDialog call");
5758
+ }
5859
5759
  return;
5860
5760
  }
5861
5761
  var script = global$5.document.createElement('script');
5862
5762
  script.async = true;
5863
- script.src = new API(options.dsn).getReportDialogEndpoint(options);
5763
+ script.src = getReportDialogEndpoint(options.dsn, options);
5864
5764
  if (options.onLoad) {
5865
5765
  // eslint-disable-next-line @typescript-eslint/unbound-method
5866
5766
  script.onload = options.onLoad;
@@ -5879,10 +5779,14 @@ var Sentry = (function (exports) {
5879
5779
  * @inheritDoc
5880
5780
  */
5881
5781
  this.name = GlobalHandlers.id;
5882
- /** JSDoc */
5883
- this._onErrorHandlerInstalled = false;
5884
- /** JSDoc */
5885
- this._onUnhandledRejectionHandlerInstalled = false;
5782
+ /**
5783
+ * Stores references functions to installing handlers. Will set to undefined
5784
+ * after they have been run so that they are not used twice.
5785
+ */
5786
+ this._installFunc = {
5787
+ onerror: _installGlobalOnErrorHandler,
5788
+ onunhandledrejection: _installGlobalOnUnhandledRejectionHandler,
5789
+ };
5886
5790
  this._options = __assign({ onerror: true, onunhandledrejection: true }, options);
5887
5791
  }
5888
5792
  /**
@@ -5890,179 +5794,183 @@ var Sentry = (function (exports) {
5890
5794
  */
5891
5795
  GlobalHandlers.prototype.setupOnce = function () {
5892
5796
  Error.stackTraceLimit = 50;
5893
- if (this._options.onerror) {
5894
- logger.log('Global Handler attached: onerror');
5895
- this._installGlobalOnErrorHandler();
5896
- }
5897
- if (this._options.onunhandledrejection) {
5898
- logger.log('Global Handler attached: onunhandledrejection');
5899
- this._installGlobalOnUnhandledRejectionHandler();
5797
+ var options = this._options;
5798
+ // We can disable guard-for-in as we construct the options object above + do checks against
5799
+ // `this._installFunc` for the property.
5800
+ // eslint-disable-next-line guard-for-in
5801
+ for (var key in options) {
5802
+ var installFunc = this._installFunc[key];
5803
+ if (installFunc && options[key]) {
5804
+ globalHandlerLog(key);
5805
+ installFunc();
5806
+ this._installFunc[key] = undefined;
5807
+ }
5900
5808
  }
5901
5809
  };
5902
- /** JSDoc */
5903
- GlobalHandlers.prototype._installGlobalOnErrorHandler = function () {
5904
- var _this = this;
5905
- if (this._onErrorHandlerInstalled) {
5810
+ /**
5811
+ * @inheritDoc
5812
+ */
5813
+ GlobalHandlers.id = 'GlobalHandlers';
5814
+ return GlobalHandlers;
5815
+ }());
5816
+ /** JSDoc */
5817
+ function _installGlobalOnErrorHandler() {
5818
+ addInstrumentationHandler('error',
5819
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
5820
+ function (data) {
5821
+ var _a = __read(getHubAndAttachStacktrace(), 2), hub = _a[0], attachStacktrace = _a[1];
5822
+ if (!hub.getIntegration(GlobalHandlers)) {
5906
5823
  return;
5907
5824
  }
5908
- addInstrumentationHandler({
5909
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
5910
- callback: function (data) {
5911
- var error = data.error;
5912
- var currentHub = getCurrentHub();
5913
- var hasIntegration = currentHub.getIntegration(GlobalHandlers);
5914
- var isFailedOwnDelivery = error && error.__sentry_own_request__ === true;
5915
- if (!hasIntegration || shouldIgnoreOnError() || isFailedOwnDelivery) {
5916
- return;
5917
- }
5918
- var client = currentHub.getClient();
5919
- var event = error === undefined && isString(data.msg)
5920
- ? _this._eventFromIncompleteOnError(data.msg, data.url, data.line, data.column)
5921
- : _this._enhanceEventWithInitialFrame(eventFromUnknownInput(error || data.msg, undefined, {
5922
- attachStacktrace: client && client.getOptions().attachStacktrace,
5923
- rejection: false,
5924
- }), data.url, data.line, data.column);
5925
- addExceptionMechanism(event, {
5926
- handled: false,
5927
- type: 'onerror',
5928
- });
5929
- currentHub.captureEvent(event, {
5930
- originalException: error,
5931
- });
5932
- },
5933
- type: 'error',
5934
- });
5935
- this._onErrorHandlerInstalled = true;
5936
- };
5937
- /** JSDoc */
5938
- GlobalHandlers.prototype._installGlobalOnUnhandledRejectionHandler = function () {
5939
- var _this = this;
5940
- if (this._onUnhandledRejectionHandlerInstalled) {
5825
+ var msg = data.msg, url = data.url, line = data.line, column = data.column, error = data.error;
5826
+ if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {
5941
5827
  return;
5942
5828
  }
5943
- addInstrumentationHandler({
5944
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
5945
- callback: function (e) {
5946
- var error = e;
5947
- // dig the object of the rejection out of known event types
5948
- try {
5949
- // PromiseRejectionEvents store the object of the rejection under 'reason'
5950
- // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent
5951
- if ('reason' in e) {
5952
- error = e.reason;
5953
- }
5954
- // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents
5955
- // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into
5956
- // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec
5957
- // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and
5958
- // https://github.com/getsentry/sentry-javascript/issues/2380
5959
- else if ('detail' in e && 'reason' in e.detail) {
5960
- error = e.detail.reason;
5961
- }
5962
- }
5963
- catch (_oO) {
5964
- // no-empty
5965
- }
5966
- var currentHub = getCurrentHub();
5967
- var hasIntegration = currentHub.getIntegration(GlobalHandlers);
5968
- var isFailedOwnDelivery = error && error.__sentry_own_request__ === true;
5969
- if (!hasIntegration || shouldIgnoreOnError() || isFailedOwnDelivery) {
5970
- return true;
5971
- }
5972
- var client = currentHub.getClient();
5973
- var event = isPrimitive(error)
5974
- ? _this._eventFromRejectionWithPrimitive(error)
5975
- : eventFromUnknownInput(error, undefined, {
5976
- attachStacktrace: client && client.getOptions().attachStacktrace,
5977
- rejection: true,
5978
- });
5979
- event.level = exports.Severity.Error;
5980
- addExceptionMechanism(event, {
5981
- handled: false,
5982
- type: 'onunhandledrejection',
5983
- });
5984
- currentHub.captureEvent(event, {
5985
- originalException: error,
5986
- });
5987
- return;
5988
- },
5989
- type: 'unhandledrejection',
5990
- });
5991
- this._onUnhandledRejectionHandlerInstalled = true;
5992
- };
5993
- /**
5994
- * This function creates a stack from an old, error-less onerror handler.
5995
- */
5996
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
5997
- GlobalHandlers.prototype._eventFromIncompleteOnError = function (msg, url, line, column) {
5998
- var ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
5999
- // If 'message' is ErrorEvent, get real message from inside
6000
- var message = isErrorEvent(msg) ? msg.message : msg;
6001
- var name;
6002
- var groups = message.match(ERROR_TYPES_RE);
6003
- if (groups) {
6004
- name = groups[1];
6005
- message = groups[2];
6006
- }
6007
- var event = {
6008
- exception: {
6009
- values: [
6010
- {
6011
- type: name || 'Error',
6012
- value: message,
6013
- },
6014
- ],
6015
- },
6016
- };
6017
- return this._enhanceEventWithInitialFrame(event, url, line, column);
6018
- };
6019
- /**
6020
- * Create an event from a promise rejection where the `reason` is a primitive.
6021
- *
6022
- * @param reason: The `reason` property of the promise rejection
6023
- * @returns An Event object with an appropriate `exception` value
6024
- */
6025
- GlobalHandlers.prototype._eventFromRejectionWithPrimitive = function (reason) {
6026
- return {
6027
- exception: {
6028
- values: [
6029
- {
6030
- type: 'UnhandledRejection',
6031
- // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)
6032
- value: "Non-Error promise rejection captured with value: " + String(reason),
6033
- },
6034
- ],
6035
- },
6036
- };
6037
- };
6038
- /** JSDoc */
5829
+ var event = error === undefined && isString(msg)
5830
+ ? _eventFromIncompleteOnError(msg, url, line, column)
5831
+ : _enhanceEventWithInitialFrame(eventFromUnknownInput(error || msg, undefined, {
5832
+ attachStacktrace: attachStacktrace,
5833
+ isRejection: false,
5834
+ }), url, line, column);
5835
+ addMechanismAndCapture(hub, error, event, 'onerror');
5836
+ });
5837
+ }
5838
+ /** JSDoc */
5839
+ function _installGlobalOnUnhandledRejectionHandler() {
5840
+ addInstrumentationHandler('unhandledrejection',
6039
5841
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
6040
- GlobalHandlers.prototype._enhanceEventWithInitialFrame = function (event, url, line, column) {
6041
- event.exception = event.exception || {};
6042
- event.exception.values = event.exception.values || [];
6043
- event.exception.values[0] = event.exception.values[0] || {};
6044
- event.exception.values[0].stacktrace = event.exception.values[0].stacktrace || {};
6045
- event.exception.values[0].stacktrace.frames = event.exception.values[0].stacktrace.frames || [];
6046
- var colno = isNaN(parseInt(column, 10)) ? undefined : column;
6047
- var lineno = isNaN(parseInt(line, 10)) ? undefined : line;
6048
- var filename = isString(url) && url.length > 0 ? url : getLocationHref();
6049
- if (event.exception.values[0].stacktrace.frames.length === 0) {
6050
- event.exception.values[0].stacktrace.frames.push({
6051
- colno: colno,
6052
- filename: filename,
6053
- function: '?',
6054
- in_app: true,
6055
- lineno: lineno,
6056
- });
5842
+ function (e) {
5843
+ var _a = __read(getHubAndAttachStacktrace(), 2), hub = _a[0], attachStacktrace = _a[1];
5844
+ if (!hub.getIntegration(GlobalHandlers)) {
5845
+ return;
6057
5846
  }
6058
- return event;
5847
+ var error = e;
5848
+ // dig the object of the rejection out of known event types
5849
+ try {
5850
+ // PromiseRejectionEvents store the object of the rejection under 'reason'
5851
+ // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent
5852
+ if ('reason' in e) {
5853
+ error = e.reason;
5854
+ }
5855
+ // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents
5856
+ // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into
5857
+ // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec
5858
+ // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and
5859
+ // https://github.com/getsentry/sentry-javascript/issues/2380
5860
+ else if ('detail' in e && 'reason' in e.detail) {
5861
+ error = e.detail.reason;
5862
+ }
5863
+ }
5864
+ catch (_oO) {
5865
+ // no-empty
5866
+ }
5867
+ if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {
5868
+ return true;
5869
+ }
5870
+ var event = isPrimitive(error)
5871
+ ? _eventFromRejectionWithPrimitive(error)
5872
+ : eventFromUnknownInput(error, undefined, {
5873
+ attachStacktrace: attachStacktrace,
5874
+ isRejection: true,
5875
+ });
5876
+ event.level = exports.Severity.Error;
5877
+ addMechanismAndCapture(hub, error, event, 'onunhandledrejection');
5878
+ return;
5879
+ });
5880
+ }
5881
+ /**
5882
+ * Create an event from a promise rejection where the `reason` is a primitive.
5883
+ *
5884
+ * @param reason: The `reason` property of the promise rejection
5885
+ * @returns An Event object with an appropriate `exception` value
5886
+ */
5887
+ function _eventFromRejectionWithPrimitive(reason) {
5888
+ return {
5889
+ exception: {
5890
+ values: [
5891
+ {
5892
+ type: 'UnhandledRejection',
5893
+ // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)
5894
+ value: "Non-Error promise rejection captured with value: " + String(reason),
5895
+ },
5896
+ ],
5897
+ },
6059
5898
  };
6060
- /**
6061
- * @inheritDoc
6062
- */
6063
- GlobalHandlers.id = 'GlobalHandlers';
6064
- return GlobalHandlers;
6065
- }());
5899
+ }
5900
+ /**
5901
+ * This function creates a stack from an old, error-less onerror handler.
5902
+ */
5903
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
5904
+ function _eventFromIncompleteOnError(msg, url, line, column) {
5905
+ var ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
5906
+ // If 'message' is ErrorEvent, get real message from inside
5907
+ var message = isErrorEvent(msg) ? msg.message : msg;
5908
+ var name = 'Error';
5909
+ var groups = message.match(ERROR_TYPES_RE);
5910
+ if (groups) {
5911
+ name = groups[1];
5912
+ message = groups[2];
5913
+ }
5914
+ var event = {
5915
+ exception: {
5916
+ values: [
5917
+ {
5918
+ type: name,
5919
+ value: message,
5920
+ },
5921
+ ],
5922
+ },
5923
+ };
5924
+ return _enhanceEventWithInitialFrame(event, url, line, column);
5925
+ }
5926
+ /** JSDoc */
5927
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
5928
+ function _enhanceEventWithInitialFrame(event, url, line, column) {
5929
+ // event.exception
5930
+ var e = (event.exception = event.exception || {});
5931
+ // event.exception.values
5932
+ var ev = (e.values = e.values || []);
5933
+ // event.exception.values[0]
5934
+ var ev0 = (ev[0] = ev[0] || {});
5935
+ // event.exception.values[0].stacktrace
5936
+ var ev0s = (ev0.stacktrace = ev0.stacktrace || {});
5937
+ // event.exception.values[0].stacktrace.frames
5938
+ var ev0sf = (ev0s.frames = ev0s.frames || []);
5939
+ var colno = isNaN(parseInt(column, 10)) ? undefined : column;
5940
+ var lineno = isNaN(parseInt(line, 10)) ? undefined : line;
5941
+ var filename = isString(url) && url.length > 0 ? url : getLocationHref();
5942
+ // event.exception.values[0].stacktrace.frames
5943
+ if (ev0sf.length === 0) {
5944
+ ev0sf.push({
5945
+ colno: colno,
5946
+ filename: filename,
5947
+ function: '?',
5948
+ in_app: true,
5949
+ lineno: lineno,
5950
+ });
5951
+ }
5952
+ return event;
5953
+ }
5954
+ function globalHandlerLog(type) {
5955
+ if (isDebugBuild()) {
5956
+ logger.log("Global Handler attached: " + type);
5957
+ }
5958
+ }
5959
+ function addMechanismAndCapture(hub, error, event, type) {
5960
+ addExceptionMechanism(event, {
5961
+ handled: false,
5962
+ type: type,
5963
+ });
5964
+ hub.captureEvent(event, {
5965
+ originalException: error,
5966
+ });
5967
+ }
5968
+ function getHubAndAttachStacktrace() {
5969
+ var hub = getCurrentHub();
5970
+ var client = hub.getClient();
5971
+ var attachStacktrace = client && client.getOptions().attachStacktrace;
5972
+ return [hub, attachStacktrace];
5973
+ }
6066
5974
 
6067
5975
  var DEFAULT_EVENT_TARGET = [
6068
5976
  'EventTarget',
@@ -6114,181 +6022,182 @@ var Sentry = (function (exports) {
6114
6022
  TryCatch.prototype.setupOnce = function () {
6115
6023
  var global = getGlobalObject();
6116
6024
  if (this._options.setTimeout) {
6117
- fill(global, 'setTimeout', this._wrapTimeFunction.bind(this));
6025
+ fill(global, 'setTimeout', _wrapTimeFunction);
6118
6026
  }
6119
6027
  if (this._options.setInterval) {
6120
- fill(global, 'setInterval', this._wrapTimeFunction.bind(this));
6028
+ fill(global, 'setInterval', _wrapTimeFunction);
6121
6029
  }
6122
6030
  if (this._options.requestAnimationFrame) {
6123
- fill(global, 'requestAnimationFrame', this._wrapRAF.bind(this));
6031
+ fill(global, 'requestAnimationFrame', _wrapRAF);
6124
6032
  }
6125
6033
  if (this._options.XMLHttpRequest && 'XMLHttpRequest' in global) {
6126
- fill(XMLHttpRequest.prototype, 'send', this._wrapXHR.bind(this));
6034
+ fill(XMLHttpRequest.prototype, 'send', _wrapXHR);
6127
6035
  }
6128
- if (this._options.eventTarget) {
6129
- var eventTarget = Array.isArray(this._options.eventTarget) ? this._options.eventTarget : DEFAULT_EVENT_TARGET;
6130
- eventTarget.forEach(this._wrapEventTarget.bind(this));
6036
+ var eventTargetOption = this._options.eventTarget;
6037
+ if (eventTargetOption) {
6038
+ var eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;
6039
+ eventTarget.forEach(_wrapEventTarget);
6131
6040
  }
6132
6041
  };
6133
- /** JSDoc */
6134
- TryCatch.prototype._wrapTimeFunction = function (original) {
6135
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
6136
- return function () {
6137
- var args = [];
6138
- for (var _i = 0; _i < arguments.length; _i++) {
6139
- args[_i] = arguments[_i];
6140
- }
6141
- var originalCallback = args[0];
6142
- args[0] = wrap(originalCallback, {
6143
- mechanism: {
6144
- data: { function: getFunctionName(original) },
6145
- handled: true,
6146
- type: 'instrument',
6147
- },
6148
- });
6149
- return original.apply(this, args);
6150
- };
6042
+ /**
6043
+ * @inheritDoc
6044
+ */
6045
+ TryCatch.id = 'TryCatch';
6046
+ return TryCatch;
6047
+ }());
6048
+ /** JSDoc */
6049
+ function _wrapTimeFunction(original) {
6050
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6051
+ return function () {
6052
+ var args = [];
6053
+ for (var _i = 0; _i < arguments.length; _i++) {
6054
+ args[_i] = arguments[_i];
6055
+ }
6056
+ var originalCallback = args[0];
6057
+ args[0] = wrap(originalCallback, {
6058
+ mechanism: {
6059
+ data: { function: getFunctionName(original) },
6060
+ handled: true,
6061
+ type: 'instrument',
6062
+ },
6063
+ });
6064
+ return original.apply(this, args);
6151
6065
  };
6152
- /** JSDoc */
6066
+ }
6067
+ /** JSDoc */
6068
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6069
+ function _wrapRAF(original) {
6153
6070
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
6154
- TryCatch.prototype._wrapRAF = function (original) {
6155
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
6156
- return function (callback) {
6157
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
6158
- return original.call(this, wrap(callback, {
6159
- mechanism: {
6160
- data: {
6161
- function: 'requestAnimationFrame',
6162
- handler: getFunctionName(original),
6163
- },
6164
- handled: true,
6165
- type: 'instrument',
6071
+ return function (callback) {
6072
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
6073
+ return original.call(this, wrap(callback, {
6074
+ mechanism: {
6075
+ data: {
6076
+ function: 'requestAnimationFrame',
6077
+ handler: getFunctionName(original),
6166
6078
  },
6167
- }));
6168
- };
6079
+ handled: true,
6080
+ type: 'instrument',
6081
+ },
6082
+ }));
6169
6083
  };
6170
- /** JSDoc */
6171
- TryCatch.prototype._wrapEventTarget = function (target) {
6172
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
6173
- var global = getGlobalObject();
6174
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
6175
- var proto = global[target] && global[target].prototype;
6176
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins
6177
- if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {
6178
- return;
6084
+ }
6085
+ /** JSDoc */
6086
+ function _wrapXHR(originalSend) {
6087
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6088
+ return function () {
6089
+ var args = [];
6090
+ for (var _i = 0; _i < arguments.length; _i++) {
6091
+ args[_i] = arguments[_i];
6179
6092
  }
6180
- fill(proto, 'addEventListener', function (original) {
6181
- return function (eventName, fn, options) {
6182
- try {
6183
- if (typeof fn.handleEvent === 'function') {
6184
- fn.handleEvent = wrap(fn.handleEvent.bind(fn), {
6185
- mechanism: {
6186
- data: {
6187
- function: 'handleEvent',
6188
- handler: getFunctionName(fn),
6189
- target: target,
6190
- },
6191
- handled: true,
6192
- type: 'instrument',
6193
- },
6194
- });
6195
- }
6196
- }
6197
- catch (err) {
6198
- // can sometimes get 'Permission denied to access property "handle Event'
6199
- }
6200
- return original.call(this, eventName,
6093
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
6094
+ var xhr = this;
6095
+ var xmlHttpRequestProps = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];
6096
+ xmlHttpRequestProps.forEach(function (prop) {
6097
+ if (prop in xhr && typeof xhr[prop] === 'function') {
6201
6098
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
6202
- wrap(fn, {
6203
- mechanism: {
6204
- data: {
6205
- function: 'addEventListener',
6206
- handler: getFunctionName(fn),
6207
- target: target,
6099
+ fill(xhr, prop, function (original) {
6100
+ var wrapOptions = {
6101
+ mechanism: {
6102
+ data: {
6103
+ function: prop,
6104
+ handler: getFunctionName(original),
6105
+ },
6106
+ handled: true,
6107
+ type: 'instrument',
6208
6108
  },
6209
- handled: true,
6210
- type: 'instrument',
6211
- },
6212
- }), options);
6213
- };
6214
- });
6215
- fill(proto, 'removeEventListener', function (originalRemoveEventListener) {
6216
- return function (eventName, fn, options) {
6217
- var _a;
6218
- /**
6219
- * There are 2 possible scenarios here:
6220
- *
6221
- * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified
6222
- * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function
6223
- * as a pass-through, and call original `removeEventListener` with it.
6224
- *
6225
- * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using
6226
- * our wrapped version of `addEventListener`, which internally calls `wrap` helper.
6227
- * This helper "wraps" whole callback inside a try/catch statement, and attached appropriate metadata to it,
6228
- * in order for us to make a distinction between wrapped/non-wrapped functions possible.
6229
- * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.
6230
- *
6231
- * When someone adds a handler prior to initialization, and then do it again, but after,
6232
- * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible
6233
- * to get rid of the initial handler and it'd stick there forever.
6234
- */
6235
- var wrappedEventHandler = fn;
6236
- try {
6237
- var originalEventHandler = (_a = wrappedEventHandler) === null || _a === void 0 ? void 0 : _a.__sentry_wrapped__;
6238
- if (originalEventHandler) {
6239
- originalRemoveEventListener.call(this, eventName, originalEventHandler, options);
6109
+ };
6110
+ // If Instrument integration has been called before TryCatch, get the name of original function
6111
+ var originalFunction = getOriginalFunction(original);
6112
+ if (originalFunction) {
6113
+ wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);
6240
6114
  }
6241
- }
6242
- catch (e) {
6243
- // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments
6244
- }
6245
- return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);
6246
- };
6115
+ // Otherwise wrap directly
6116
+ return wrap(original, wrapOptions);
6117
+ });
6118
+ }
6247
6119
  });
6120
+ return originalSend.apply(this, args);
6248
6121
  };
6249
- /** JSDoc */
6250
- TryCatch.prototype._wrapXHR = function (originalSend) {
6251
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
6252
- return function () {
6253
- var args = [];
6254
- for (var _i = 0; _i < arguments.length; _i++) {
6255
- args[_i] = arguments[_i];
6256
- }
6257
- // eslint-disable-next-line @typescript-eslint/no-this-alias
6258
- var xhr = this;
6259
- var xmlHttpRequestProps = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];
6260
- xmlHttpRequestProps.forEach(function (prop) {
6261
- if (prop in xhr && typeof xhr[prop] === 'function') {
6262
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
6263
- fill(xhr, prop, function (original) {
6264
- var wrapOptions = {
6265
- mechanism: {
6266
- data: {
6267
- function: prop,
6268
- handler: getFunctionName(original),
6269
- },
6270
- handled: true,
6271
- type: 'instrument',
6122
+ }
6123
+ /** JSDoc */
6124
+ function _wrapEventTarget(target) {
6125
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6126
+ var global = getGlobalObject();
6127
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
6128
+ var proto = global[target] && global[target].prototype;
6129
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins
6130
+ if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {
6131
+ return;
6132
+ }
6133
+ fill(proto, 'addEventListener', function (original) {
6134
+ return function (eventName, fn, options) {
6135
+ try {
6136
+ if (typeof fn.handleEvent === 'function') {
6137
+ fn.handleEvent = wrap(fn.handleEvent.bind(fn), {
6138
+ mechanism: {
6139
+ data: {
6140
+ function: 'handleEvent',
6141
+ handler: getFunctionName(fn),
6142
+ target: target,
6272
6143
  },
6273
- };
6274
- // If Instrument integration has been called before TryCatch, get the name of original function
6275
- if (original.__sentry_original__) {
6276
- wrapOptions.mechanism.data.handler = getFunctionName(original.__sentry_original__);
6277
- }
6278
- // Otherwise wrap directly
6279
- return wrap(original, wrapOptions);
6144
+ handled: true,
6145
+ type: 'instrument',
6146
+ },
6280
6147
  });
6281
6148
  }
6282
- });
6283
- return originalSend.apply(this, args);
6149
+ }
6150
+ catch (err) {
6151
+ // can sometimes get 'Permission denied to access property "handle Event'
6152
+ }
6153
+ return original.call(this, eventName,
6154
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6155
+ wrap(fn, {
6156
+ mechanism: {
6157
+ data: {
6158
+ function: 'addEventListener',
6159
+ handler: getFunctionName(fn),
6160
+ target: target,
6161
+ },
6162
+ handled: true,
6163
+ type: 'instrument',
6164
+ },
6165
+ }), options);
6284
6166
  };
6285
- };
6286
- /**
6287
- * @inheritDoc
6288
- */
6289
- TryCatch.id = 'TryCatch';
6290
- return TryCatch;
6291
- }());
6167
+ });
6168
+ fill(proto, 'removeEventListener', function (originalRemoveEventListener) {
6169
+ return function (eventName, fn, options) {
6170
+ /**
6171
+ * There are 2 possible scenarios here:
6172
+ *
6173
+ * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified
6174
+ * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function
6175
+ * as a pass-through, and call original `removeEventListener` with it.
6176
+ *
6177
+ * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using
6178
+ * our wrapped version of `addEventListener`, which internally calls `wrap` helper.
6179
+ * This helper "wraps" whole callback inside a try/catch statement, and attached appropriate metadata to it,
6180
+ * in order for us to make a distinction between wrapped/non-wrapped functions possible.
6181
+ * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.
6182
+ *
6183
+ * When someone adds a handler prior to initialization, and then do it again, but after,
6184
+ * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible
6185
+ * to get rid of the initial handler and it'd stick there forever.
6186
+ */
6187
+ var wrappedEventHandler = fn;
6188
+ try {
6189
+ var originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;
6190
+ if (originalEventHandler) {
6191
+ originalRemoveEventListener.call(this, eventName, originalEventHandler, options);
6192
+ }
6193
+ }
6194
+ catch (e) {
6195
+ // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments
6196
+ }
6197
+ return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);
6198
+ };
6199
+ });
6200
+ }
6292
6201
 
6293
6202
  /**
6294
6203
  * Default Breadcrumbs instrumentations
@@ -6330,104 +6239,38 @@ var Sentry = (function (exports) {
6330
6239
  * - History API
6331
6240
  */
6332
6241
  Breadcrumbs.prototype.setupOnce = function () {
6333
- var _this = this;
6334
6242
  if (this._options.console) {
6335
- addInstrumentationHandler({
6336
- callback: function () {
6337
- var args = [];
6338
- for (var _i = 0; _i < arguments.length; _i++) {
6339
- args[_i] = arguments[_i];
6340
- }
6341
- _this._consoleBreadcrumb.apply(_this, __spread(args));
6342
- },
6343
- type: 'console',
6344
- });
6243
+ addInstrumentationHandler('console', _consoleBreadcrumb);
6345
6244
  }
6346
6245
  if (this._options.dom) {
6347
- addInstrumentationHandler({
6348
- callback: function () {
6349
- var args = [];
6350
- for (var _i = 0; _i < arguments.length; _i++) {
6351
- args[_i] = arguments[_i];
6352
- }
6353
- _this._domBreadcrumb.apply(_this, __spread(args));
6354
- },
6355
- type: 'dom',
6356
- });
6246
+ addInstrumentationHandler('dom', _domBreadcrumb(this._options.dom));
6357
6247
  }
6358
6248
  if (this._options.xhr) {
6359
- addInstrumentationHandler({
6360
- callback: function () {
6361
- var args = [];
6362
- for (var _i = 0; _i < arguments.length; _i++) {
6363
- args[_i] = arguments[_i];
6364
- }
6365
- _this._xhrBreadcrumb.apply(_this, __spread(args));
6366
- },
6367
- type: 'xhr',
6368
- });
6249
+ addInstrumentationHandler('xhr', _xhrBreadcrumb);
6369
6250
  }
6370
6251
  if (this._options.fetch) {
6371
- addInstrumentationHandler({
6372
- callback: function () {
6373
- var args = [];
6374
- for (var _i = 0; _i < arguments.length; _i++) {
6375
- args[_i] = arguments[_i];
6376
- }
6377
- _this._fetchBreadcrumb.apply(_this, __spread(args));
6378
- },
6379
- type: 'fetch',
6380
- });
6252
+ addInstrumentationHandler('fetch', _fetchBreadcrumb);
6381
6253
  }
6382
6254
  if (this._options.history) {
6383
- addInstrumentationHandler({
6384
- callback: function () {
6385
- var args = [];
6386
- for (var _i = 0; _i < arguments.length; _i++) {
6387
- args[_i] = arguments[_i];
6388
- }
6389
- _this._historyBreadcrumb.apply(_this, __spread(args));
6390
- },
6391
- type: 'history',
6392
- });
6393
- }
6394
- };
6395
- /**
6396
- * Creates breadcrumbs from console API calls
6397
- */
6398
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
6399
- Breadcrumbs.prototype._consoleBreadcrumb = function (handlerData) {
6400
- var breadcrumb = {
6401
- category: 'console',
6402
- data: {
6403
- arguments: handlerData.args,
6404
- logger: 'console',
6405
- },
6406
- level: exports.Severity.fromString(handlerData.level),
6407
- message: safeJoin(handlerData.args, ' '),
6408
- };
6409
- if (handlerData.level === 'assert') {
6410
- if (handlerData.args[0] === false) {
6411
- breadcrumb.message = "Assertion failed: " + (safeJoin(handlerData.args.slice(1), ' ') || 'console.assert');
6412
- breadcrumb.data.arguments = handlerData.args.slice(1);
6413
- }
6414
- else {
6415
- // Don't capture a breadcrumb for passed assertions
6416
- return;
6417
- }
6255
+ addInstrumentationHandler('history', _historyBreadcrumb);
6418
6256
  }
6419
- getCurrentHub().addBreadcrumb(breadcrumb, {
6420
- input: handlerData.args,
6421
- level: handlerData.level,
6422
- });
6423
6257
  };
6424
6258
  /**
6425
- * Creates breadcrumbs from DOM API calls
6259
+ * @inheritDoc
6426
6260
  */
6261
+ Breadcrumbs.id = 'Breadcrumbs';
6262
+ return Breadcrumbs;
6263
+ }());
6264
+ /**
6265
+ * A HOC that creaes a function that creates breadcrumbs from DOM API calls.
6266
+ * This is a HOC so that we get access to dom options in the closure.
6267
+ */
6268
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6269
+ function _domBreadcrumb(dom) {
6427
6270
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
6428
- Breadcrumbs.prototype._domBreadcrumb = function (handlerData) {
6271
+ function _innerDomBreadcrumb(handlerData) {
6429
6272
  var target;
6430
- var keyAttrs = typeof this._options.dom === 'object' ? this._options.dom.serializeAttribute : undefined;
6273
+ var keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;
6431
6274
  if (typeof keyAttrs === 'string') {
6432
6275
  keyAttrs = [keyAttrs];
6433
6276
  }
@@ -6451,105 +6294,130 @@ var Sentry = (function (exports) {
6451
6294
  name: handlerData.name,
6452
6295
  global: handlerData.global,
6453
6296
  });
6297
+ }
6298
+ return _innerDomBreadcrumb;
6299
+ }
6300
+ /**
6301
+ * Creates breadcrumbs from console API calls
6302
+ */
6303
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6304
+ function _consoleBreadcrumb(handlerData) {
6305
+ var breadcrumb = {
6306
+ category: 'console',
6307
+ data: {
6308
+ arguments: handlerData.args,
6309
+ logger: 'console',
6310
+ },
6311
+ level: severityFromString(handlerData.level),
6312
+ message: safeJoin(handlerData.args, ' '),
6454
6313
  };
6455
- /**
6456
- * Creates breadcrumbs from XHR API calls
6457
- */
6458
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
6459
- Breadcrumbs.prototype._xhrBreadcrumb = function (handlerData) {
6460
- if (handlerData.endTimestamp) {
6461
- // We only capture complete, non-sentry requests
6462
- if (handlerData.xhr.__sentry_own_request__) {
6463
- return;
6464
- }
6465
- var _a = handlerData.xhr.__sentry_xhr__ || {}, method = _a.method, url = _a.url, status_code = _a.status_code, body = _a.body;
6466
- getCurrentHub().addBreadcrumb({
6467
- category: 'xhr',
6468
- data: {
6469
- method: method,
6470
- url: url,
6471
- status_code: status_code,
6472
- },
6473
- type: 'http',
6474
- }, {
6475
- xhr: handlerData.xhr,
6476
- input: body,
6477
- });
6478
- return;
6314
+ if (handlerData.level === 'assert') {
6315
+ if (handlerData.args[0] === false) {
6316
+ breadcrumb.message = "Assertion failed: " + (safeJoin(handlerData.args.slice(1), ' ') || 'console.assert');
6317
+ breadcrumb.data.arguments = handlerData.args.slice(1);
6479
6318
  }
6480
- };
6481
- /**
6482
- * Creates breadcrumbs from fetch API calls
6483
- */
6484
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
6485
- Breadcrumbs.prototype._fetchBreadcrumb = function (handlerData) {
6486
- // We only capture complete fetch requests
6487
- if (!handlerData.endTimestamp) {
6319
+ else {
6320
+ // Don't capture a breadcrumb for passed assertions
6488
6321
  return;
6489
6322
  }
6490
- if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {
6491
- // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)
6323
+ }
6324
+ getCurrentHub().addBreadcrumb(breadcrumb, {
6325
+ input: handlerData.args,
6326
+ level: handlerData.level,
6327
+ });
6328
+ }
6329
+ /**
6330
+ * Creates breadcrumbs from XHR API calls
6331
+ */
6332
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6333
+ function _xhrBreadcrumb(handlerData) {
6334
+ if (handlerData.endTimestamp) {
6335
+ // We only capture complete, non-sentry requests
6336
+ if (handlerData.xhr.__sentry_own_request__) {
6492
6337
  return;
6493
6338
  }
6494
- if (handlerData.error) {
6495
- getCurrentHub().addBreadcrumb({
6496
- category: 'fetch',
6497
- data: handlerData.fetchData,
6498
- level: exports.Severity.Error,
6499
- type: 'http',
6500
- }, {
6501
- data: handlerData.error,
6502
- input: handlerData.args,
6503
- });
6504
- }
6505
- else {
6506
- getCurrentHub().addBreadcrumb({
6507
- category: 'fetch',
6508
- data: __assign(__assign({}, handlerData.fetchData), { status_code: handlerData.response.status }),
6509
- type: 'http',
6510
- }, {
6511
- input: handlerData.args,
6512
- response: handlerData.response,
6513
- });
6514
- }
6515
- };
6516
- /**
6517
- * Creates breadcrumbs from history API calls
6518
- */
6519
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
6520
- Breadcrumbs.prototype._historyBreadcrumb = function (handlerData) {
6521
- var global = getGlobalObject();
6522
- var from = handlerData.from;
6523
- var to = handlerData.to;
6524
- var parsedLoc = parseUrl(global.location.href);
6525
- var parsedFrom = parseUrl(from);
6526
- var parsedTo = parseUrl(to);
6527
- // Initial pushState doesn't provide `from` information
6528
- if (!parsedFrom.path) {
6529
- parsedFrom = parsedLoc;
6530
- }
6531
- // Use only the path component of the URL if the URL matches the current
6532
- // document (almost all the time when using pushState)
6533
- if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {
6534
- to = parsedTo.relative;
6535
- }
6536
- if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {
6537
- from = parsedFrom.relative;
6538
- }
6339
+ var _a = handlerData.xhr.__sentry_xhr__ || {}, method = _a.method, url = _a.url, status_code = _a.status_code, body = _a.body;
6539
6340
  getCurrentHub().addBreadcrumb({
6540
- category: 'navigation',
6341
+ category: 'xhr',
6541
6342
  data: {
6542
- from: from,
6543
- to: to,
6343
+ method: method,
6344
+ url: url,
6345
+ status_code: status_code,
6544
6346
  },
6347
+ type: 'http',
6348
+ }, {
6349
+ xhr: handlerData.xhr,
6350
+ input: body,
6545
6351
  });
6546
- };
6547
- /**
6548
- * @inheritDoc
6549
- */
6550
- Breadcrumbs.id = 'Breadcrumbs';
6551
- return Breadcrumbs;
6552
- }());
6352
+ return;
6353
+ }
6354
+ }
6355
+ /**
6356
+ * Creates breadcrumbs from fetch API calls
6357
+ */
6358
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6359
+ function _fetchBreadcrumb(handlerData) {
6360
+ // We only capture complete fetch requests
6361
+ if (!handlerData.endTimestamp) {
6362
+ return;
6363
+ }
6364
+ if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {
6365
+ // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)
6366
+ return;
6367
+ }
6368
+ if (handlerData.error) {
6369
+ getCurrentHub().addBreadcrumb({
6370
+ category: 'fetch',
6371
+ data: handlerData.fetchData,
6372
+ level: exports.Severity.Error,
6373
+ type: 'http',
6374
+ }, {
6375
+ data: handlerData.error,
6376
+ input: handlerData.args,
6377
+ });
6378
+ }
6379
+ else {
6380
+ getCurrentHub().addBreadcrumb({
6381
+ category: 'fetch',
6382
+ data: __assign(__assign({}, handlerData.fetchData), { status_code: handlerData.response.status }),
6383
+ type: 'http',
6384
+ }, {
6385
+ input: handlerData.args,
6386
+ response: handlerData.response,
6387
+ });
6388
+ }
6389
+ }
6390
+ /**
6391
+ * Creates breadcrumbs from history API calls
6392
+ */
6393
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6394
+ function _historyBreadcrumb(handlerData) {
6395
+ var global = getGlobalObject();
6396
+ var from = handlerData.from;
6397
+ var to = handlerData.to;
6398
+ var parsedLoc = parseUrl(global.location.href);
6399
+ var parsedFrom = parseUrl(from);
6400
+ var parsedTo = parseUrl(to);
6401
+ // Initial pushState doesn't provide `from` information
6402
+ if (!parsedFrom.path) {
6403
+ parsedFrom = parsedLoc;
6404
+ }
6405
+ // Use only the path component of the URL if the URL matches the current
6406
+ // document (almost all the time when using pushState)
6407
+ if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {
6408
+ to = parsedTo.relative;
6409
+ }
6410
+ if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {
6411
+ from = parsedFrom.relative;
6412
+ }
6413
+ getCurrentHub().addBreadcrumb({
6414
+ category: 'navigation',
6415
+ data: {
6416
+ from: from,
6417
+ to: to,
6418
+ },
6419
+ });
6420
+ }
6553
6421
 
6554
6422
  var DEFAULT_KEY = 'cause';
6555
6423
  var DEFAULT_LIMIT = 5;
@@ -6573,42 +6441,38 @@ var Sentry = (function (exports) {
6573
6441
  LinkedErrors.prototype.setupOnce = function () {
6574
6442
  addGlobalEventProcessor(function (event, hint) {
6575
6443
  var self = getCurrentHub().getIntegration(LinkedErrors);
6576
- if (self) {
6577
- var handler = self._handler && self._handler.bind(self);
6578
- return typeof handler === 'function' ? handler(event, hint) : event;
6579
- }
6580
- return event;
6444
+ return self ? _handler(self._key, self._limit, event, hint) : event;
6581
6445
  });
6582
6446
  };
6583
- /**
6584
- * @inheritDoc
6585
- */
6586
- LinkedErrors.prototype._handler = function (event, hint) {
6587
- if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {
6588
- return event;
6589
- }
6590
- var linkedErrors = this._walkErrorTree(hint.originalException, this._key);
6591
- event.exception.values = __spread(linkedErrors, event.exception.values);
6592
- return event;
6593
- };
6594
- /**
6595
- * @inheritDoc
6596
- */
6597
- LinkedErrors.prototype._walkErrorTree = function (error, key, stack) {
6598
- if (stack === void 0) { stack = []; }
6599
- if (!isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) {
6600
- return stack;
6601
- }
6602
- var stacktrace = computeStackTrace(error[key]);
6603
- var exception = exceptionFromStacktrace(stacktrace);
6604
- return this._walkErrorTree(error[key], key, __spread([exception], stack));
6605
- };
6606
6447
  /**
6607
6448
  * @inheritDoc
6608
6449
  */
6609
6450
  LinkedErrors.id = 'LinkedErrors';
6610
6451
  return LinkedErrors;
6611
- }());
6452
+ }());
6453
+ /**
6454
+ * @inheritDoc
6455
+ */
6456
+ function _handler(key, limit, event, hint) {
6457
+ if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {
6458
+ return event;
6459
+ }
6460
+ var linkedErrors = _walkErrorTree(limit, hint.originalException, key);
6461
+ event.exception.values = __spread(linkedErrors, event.exception.values);
6462
+ return event;
6463
+ }
6464
+ /**
6465
+ * JSDOC
6466
+ */
6467
+ function _walkErrorTree(limit, error, key, stack) {
6468
+ if (stack === void 0) { stack = []; }
6469
+ if (!isInstanceOf(error[key], Error) || stack.length + 1 >= limit) {
6470
+ return stack;
6471
+ }
6472
+ var stacktrace = computeStackTrace(error[key]);
6473
+ var exception = exceptionFromStacktrace(stacktrace);
6474
+ return _walkErrorTree(limit, error[key], key, __spread([exception], stack));
6475
+ }
6612
6476
 
6613
6477
  var global$6 = getGlobalObject();
6614
6478
  /** UserAgent */
@@ -6624,17 +6488,16 @@ var Sentry = (function (exports) {
6624
6488
  */
6625
6489
  UserAgent.prototype.setupOnce = function () {
6626
6490
  addGlobalEventProcessor(function (event) {
6627
- var _a, _b, _c;
6628
6491
  if (getCurrentHub().getIntegration(UserAgent)) {
6629
6492
  // if none of the information we want exists, don't bother
6630
6493
  if (!global$6.navigator && !global$6.location && !global$6.document) {
6631
6494
  return event;
6632
6495
  }
6633
6496
  // grab as much info as exists and add it to the event
6634
- var url = ((_a = event.request) === null || _a === void 0 ? void 0 : _a.url) || ((_b = global$6.location) === null || _b === void 0 ? void 0 : _b.href);
6497
+ var url = (event.request && event.request.url) || (global$6.location && global$6.location.href);
6635
6498
  var referrer = (global$6.document || {}).referrer;
6636
6499
  var userAgent = (global$6.navigator || {}).userAgent;
6637
- var headers = __assign(__assign(__assign({}, (_c = event.request) === null || _c === void 0 ? void 0 : _c.headers), (referrer && { Referer: referrer })), (userAgent && { 'User-Agent': userAgent }));
6500
+ var headers = __assign(__assign(__assign({}, (event.request && event.request.headers)), (referrer && { Referer: referrer })), (userAgent && { 'User-Agent': userAgent }));
6638
6501
  var request = __assign(__assign({}, (url && { url: url })), { headers: headers });
6639
6502
  return __assign(__assign({}, event), { request: request });
6640
6503
  }
@@ -6665,7 +6528,7 @@ var Sentry = (function (exports) {
6665
6528
  if (self) {
6666
6529
  // Juuust in case something goes wrong
6667
6530
  try {
6668
- if (self._shouldDropEvent(currentEvent, self._previousEvent)) {
6531
+ if (_shouldDropEvent(currentEvent, self._previousEvent)) {
6669
6532
  logger.warn("Event dropped due to being a duplicate of previously captured event.");
6670
6533
  return null;
6671
6534
  }
@@ -6678,140 +6541,140 @@ var Sentry = (function (exports) {
6678
6541
  return currentEvent;
6679
6542
  });
6680
6543
  };
6681
- /** JSDoc */
6682
- Dedupe.prototype._shouldDropEvent = function (currentEvent, previousEvent) {
6683
- if (!previousEvent) {
6684
- return false;
6685
- }
6686
- if (this._isSameMessageEvent(currentEvent, previousEvent)) {
6687
- return true;
6688
- }
6689
- if (this._isSameExceptionEvent(currentEvent, previousEvent)) {
6690
- return true;
6691
- }
6544
+ /**
6545
+ * @inheritDoc
6546
+ */
6547
+ Dedupe.id = 'Dedupe';
6548
+ return Dedupe;
6549
+ }());
6550
+ /** JSDoc */
6551
+ function _shouldDropEvent(currentEvent, previousEvent) {
6552
+ if (!previousEvent) {
6692
6553
  return false;
6693
- };
6694
- /** JSDoc */
6695
- Dedupe.prototype._isSameMessageEvent = function (currentEvent, previousEvent) {
6696
- var currentMessage = currentEvent.message;
6697
- var previousMessage = previousEvent.message;
6698
- // If neither event has a message property, they were both exceptions, so bail out
6699
- if (!currentMessage && !previousMessage) {
6700
- return false;
6701
- }
6702
- // If only one event has a stacktrace, but not the other one, they are not the same
6703
- if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {
6704
- return false;
6705
- }
6706
- if (currentMessage !== previousMessage) {
6707
- return false;
6708
- }
6709
- if (!this._isSameFingerprint(currentEvent, previousEvent)) {
6710
- return false;
6711
- }
6712
- if (!this._isSameStacktrace(currentEvent, previousEvent)) {
6713
- return false;
6714
- }
6554
+ }
6555
+ if (_isSameMessageEvent(currentEvent, previousEvent)) {
6715
6556
  return true;
6716
- };
6717
- /** JSDoc */
6718
- Dedupe.prototype._getFramesFromEvent = function (event) {
6719
- var exception = event.exception;
6720
- if (exception) {
6721
- try {
6722
- // @ts-ignore Object could be undefined
6723
- return exception.values[0].stacktrace.frames;
6724
- }
6725
- catch (_oO) {
6726
- return undefined;
6727
- }
6728
- }
6729
- else if (event.stacktrace) {
6730
- return event.stacktrace.frames;
6731
- }
6732
- return undefined;
6733
- };
6734
- /** JSDoc */
6735
- Dedupe.prototype._isSameStacktrace = function (currentEvent, previousEvent) {
6736
- var currentFrames = this._getFramesFromEvent(currentEvent);
6737
- var previousFrames = this._getFramesFromEvent(previousEvent);
6738
- // If neither event has a stacktrace, they are assumed to be the same
6739
- if (!currentFrames && !previousFrames) {
6740
- return true;
6741
- }
6742
- // If only one event has a stacktrace, but not the other one, they are not the same
6743
- if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {
6744
- return false;
6745
- }
6746
- currentFrames = currentFrames;
6747
- previousFrames = previousFrames;
6748
- // If number of frames differ, they are not the same
6749
- if (previousFrames.length !== currentFrames.length) {
6750
- return false;
6751
- }
6752
- // Otherwise, compare the two
6753
- for (var i = 0; i < previousFrames.length; i++) {
6754
- var frameA = previousFrames[i];
6755
- var frameB = currentFrames[i];
6756
- if (frameA.filename !== frameB.filename ||
6757
- frameA.lineno !== frameB.lineno ||
6758
- frameA.colno !== frameB.colno ||
6759
- frameA.function !== frameB.function) {
6760
- return false;
6761
- }
6762
- }
6557
+ }
6558
+ if (_isSameExceptionEvent(currentEvent, previousEvent)) {
6763
6559
  return true;
6764
- };
6765
- /** JSDoc */
6766
- Dedupe.prototype._getExceptionFromEvent = function (event) {
6767
- return event.exception && event.exception.values && event.exception.values[0];
6768
- };
6769
- /** JSDoc */
6770
- Dedupe.prototype._isSameExceptionEvent = function (currentEvent, previousEvent) {
6771
- var previousException = this._getExceptionFromEvent(previousEvent);
6772
- var currentException = this._getExceptionFromEvent(currentEvent);
6773
- if (!previousException || !currentException) {
6774
- return false;
6775
- }
6776
- if (previousException.type !== currentException.type || previousException.value !== currentException.value) {
6777
- return false;
6778
- }
6779
- if (!this._isSameFingerprint(currentEvent, previousEvent)) {
6780
- return false;
6781
- }
6782
- if (!this._isSameStacktrace(currentEvent, previousEvent)) {
6783
- return false;
6784
- }
6560
+ }
6561
+ return false;
6562
+ }
6563
+ /** JSDoc */
6564
+ function _isSameMessageEvent(currentEvent, previousEvent) {
6565
+ var currentMessage = currentEvent.message;
6566
+ var previousMessage = previousEvent.message;
6567
+ // If neither event has a message property, they were both exceptions, so bail out
6568
+ if (!currentMessage && !previousMessage) {
6569
+ return false;
6570
+ }
6571
+ // If only one event has a stacktrace, but not the other one, they are not the same
6572
+ if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {
6573
+ return false;
6574
+ }
6575
+ if (currentMessage !== previousMessage) {
6576
+ return false;
6577
+ }
6578
+ if (!_isSameFingerprint(currentEvent, previousEvent)) {
6579
+ return false;
6580
+ }
6581
+ if (!_isSameStacktrace(currentEvent, previousEvent)) {
6582
+ return false;
6583
+ }
6584
+ return true;
6585
+ }
6586
+ /** JSDoc */
6587
+ function _isSameExceptionEvent(currentEvent, previousEvent) {
6588
+ var previousException = _getExceptionFromEvent(previousEvent);
6589
+ var currentException = _getExceptionFromEvent(currentEvent);
6590
+ if (!previousException || !currentException) {
6591
+ return false;
6592
+ }
6593
+ if (previousException.type !== currentException.type || previousException.value !== currentException.value) {
6594
+ return false;
6595
+ }
6596
+ if (!_isSameFingerprint(currentEvent, previousEvent)) {
6597
+ return false;
6598
+ }
6599
+ if (!_isSameStacktrace(currentEvent, previousEvent)) {
6600
+ return false;
6601
+ }
6602
+ return true;
6603
+ }
6604
+ /** JSDoc */
6605
+ function _isSameStacktrace(currentEvent, previousEvent) {
6606
+ var currentFrames = _getFramesFromEvent(currentEvent);
6607
+ var previousFrames = _getFramesFromEvent(previousEvent);
6608
+ // If neither event has a stacktrace, they are assumed to be the same
6609
+ if (!currentFrames && !previousFrames) {
6785
6610
  return true;
6786
- };
6787
- /** JSDoc */
6788
- Dedupe.prototype._isSameFingerprint = function (currentEvent, previousEvent) {
6789
- var currentFingerprint = currentEvent.fingerprint;
6790
- var previousFingerprint = previousEvent.fingerprint;
6791
- // If neither event has a fingerprint, they are assumed to be the same
6792
- if (!currentFingerprint && !previousFingerprint) {
6793
- return true;
6794
- }
6795
- // If only one event has a fingerprint, but not the other one, they are not the same
6796
- if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {
6611
+ }
6612
+ // If only one event has a stacktrace, but not the other one, they are not the same
6613
+ if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {
6614
+ return false;
6615
+ }
6616
+ currentFrames = currentFrames;
6617
+ previousFrames = previousFrames;
6618
+ // If number of frames differ, they are not the same
6619
+ if (previousFrames.length !== currentFrames.length) {
6620
+ return false;
6621
+ }
6622
+ // Otherwise, compare the two
6623
+ for (var i = 0; i < previousFrames.length; i++) {
6624
+ var frameA = previousFrames[i];
6625
+ var frameB = currentFrames[i];
6626
+ if (frameA.filename !== frameB.filename ||
6627
+ frameA.lineno !== frameB.lineno ||
6628
+ frameA.colno !== frameB.colno ||
6629
+ frameA.function !== frameB.function) {
6797
6630
  return false;
6798
6631
  }
6799
- currentFingerprint = currentFingerprint;
6800
- previousFingerprint = previousFingerprint;
6801
- // Otherwise, compare the two
6632
+ }
6633
+ return true;
6634
+ }
6635
+ /** JSDoc */
6636
+ function _isSameFingerprint(currentEvent, previousEvent) {
6637
+ var currentFingerprint = currentEvent.fingerprint;
6638
+ var previousFingerprint = previousEvent.fingerprint;
6639
+ // If neither event has a fingerprint, they are assumed to be the same
6640
+ if (!currentFingerprint && !previousFingerprint) {
6641
+ return true;
6642
+ }
6643
+ // If only one event has a fingerprint, but not the other one, they are not the same
6644
+ if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {
6645
+ return false;
6646
+ }
6647
+ currentFingerprint = currentFingerprint;
6648
+ previousFingerprint = previousFingerprint;
6649
+ // Otherwise, compare the two
6650
+ try {
6651
+ return !!(currentFingerprint.join('') === previousFingerprint.join(''));
6652
+ }
6653
+ catch (_oO) {
6654
+ return false;
6655
+ }
6656
+ }
6657
+ /** JSDoc */
6658
+ function _getExceptionFromEvent(event) {
6659
+ return event.exception && event.exception.values && event.exception.values[0];
6660
+ }
6661
+ /** JSDoc */
6662
+ function _getFramesFromEvent(event) {
6663
+ var exception = event.exception;
6664
+ if (exception) {
6802
6665
  try {
6803
- return !!(currentFingerprint.join('') === previousFingerprint.join(''));
6666
+ // @ts-ignore Object could be undefined
6667
+ return exception.values[0].stacktrace.frames;
6804
6668
  }
6805
6669
  catch (_oO) {
6806
- return false;
6670
+ return undefined;
6807
6671
  }
6808
- };
6809
- /**
6810
- * @inheritDoc
6811
- */
6812
- Dedupe.id = 'Dedupe';
6813
- return Dedupe;
6814
- }());
6672
+ }
6673
+ else if (event.stacktrace) {
6674
+ return event.stacktrace.frames;
6675
+ }
6676
+ return undefined;
6677
+ }
6815
6678
 
6816
6679
 
6817
6680
 
@@ -7038,8 +6901,10 @@ var Sentry = (function (exports) {
7038
6901
  if (client) {
7039
6902
  return client.flush(timeout);
7040
6903
  }
7041
- logger.warn('Cannot flush events. No client defined.');
7042
- return SyncPromise.resolve(false);
6904
+ if (isDebugBuild()) {
6905
+ logger.warn('Cannot flush events. No client defined.');
6906
+ }
6907
+ return resolvedSyncPromise(false);
7043
6908
  }
7044
6909
  /**
7045
6910
  * Call `close()` on the current client, if there is one. See {@link Client.close}.
@@ -7054,8 +6919,10 @@ var Sentry = (function (exports) {
7054
6919
  if (client) {
7055
6920
  return client.close(timeout);
7056
6921
  }
7057
- logger.warn('Cannot flush events and disable SDK. No client defined.');
7058
- return SyncPromise.resolve(false);
6922
+ if (isDebugBuild()) {
6923
+ logger.warn('Cannot flush events and disable SDK. No client defined.');
6924
+ }
6925
+ return resolvedSyncPromise(false);
7059
6926
  }
7060
6927
  /**
7061
6928
  * Wrap code within a try/catch block so the SDK is able to capture errors.
@@ -7068,6 +6935,10 @@ var Sentry = (function (exports) {
7068
6935
  function wrap$1(fn) {
7069
6936
  return wrap(fn)();
7070
6937
  }
6938
+ function startSessionOnHub(hub) {
6939
+ hub.startSession({ ignoreDuration: true });
6940
+ hub.captureSession();
6941
+ }
7071
6942
  /**
7072
6943
  * Enable automatic Session Tracking for the initial page load.
7073
6944
  */
@@ -7075,7 +6946,9 @@ var Sentry = (function (exports) {
7075
6946
  var window = getGlobalObject();
7076
6947
  var document = window.document;
7077
6948
  if (typeof document === 'undefined') {
7078
- logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');
6949
+ if (isDebugBuild()) {
6950
+ logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');
6951
+ }
7079
6952
  return;
7080
6953
  }
7081
6954
  var hub = getCurrentHub();
@@ -7085,27 +6958,21 @@ var Sentry = (function (exports) {
7085
6958
  // https://github.com/getsentry/sentry-javascript/issues/3207 and
7086
6959
  // https://github.com/getsentry/sentry-javascript/issues/3234 and
7087
6960
  // https://github.com/getsentry/sentry-javascript/issues/3278.
7088
- if (typeof hub.startSession !== 'function' || typeof hub.captureSession !== 'function') {
6961
+ if (!hub.captureSession) {
7089
6962
  return;
7090
6963
  }
7091
6964
  // The session duration for browser sessions does not track a meaningful
7092
6965
  // concept that can be used as a metric.
7093
6966
  // Automatically captured sessions are akin to page views, and thus we
7094
6967
  // discard their duration.
7095
- hub.startSession({ ignoreDuration: true });
7096
- hub.captureSession();
6968
+ startSessionOnHub(hub);
7097
6969
  // We want to create a session for every navigation as well
7098
- addInstrumentationHandler({
7099
- callback: function (_a) {
7100
- var from = _a.from, to = _a.to;
7101
- // Don't create an additional session for the initial route or if the location did not change
7102
- if (from === undefined || from === to) {
7103
- return;
7104
- }
7105
- hub.startSession({ ignoreDuration: true });
7106
- hub.captureSession();
7107
- },
7108
- type: 'history',
6970
+ addInstrumentationHandler('history', function (_a) {
6971
+ var from = _a.from, to = _a.to;
6972
+ // Don't create an additional session for the initial route or if the location did not change
6973
+ if (!(from === undefined || from === to)) {
6974
+ startSessionOnHub(getCurrentHub());
6975
+ }
7109
6976
  });
7110
6977
  }
7111
6978