@honeybadger-io/js 4.0.3 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +13 -64
  2. package/dist/browser/honeybadger.d.ts +6 -6
  3. package/dist/browser/honeybadger.js +1791 -1694
  4. package/dist/browser/honeybadger.js.map +1 -1
  5. package/dist/browser/honeybadger.min.js +1 -1
  6. package/dist/browser/honeybadger.min.js.map +1 -1
  7. package/dist/browser/integrations/breadcrumbs.d.ts +3 -0
  8. package/dist/browser/integrations/event_listeners.d.ts +3 -0
  9. package/dist/browser/integrations/onerror.d.ts +4 -0
  10. package/dist/browser/integrations/onunhandledrejection.d.ts +3 -0
  11. package/dist/browser/integrations/timers.d.ts +3 -0
  12. package/dist/browser/transport.d.ts +8 -0
  13. package/dist/browser/{types/browser/util.d.ts → util.d.ts} +1 -0
  14. package/dist/server/async_store.d.ts +6 -0
  15. package/dist/server/{types/server/aws_lambda.d.ts → aws_lambda.d.ts} +1 -1
  16. package/dist/server/honeybadger.d.ts +8 -8
  17. package/dist/server/honeybadger.js +644 -504
  18. package/dist/server/integrations/uncaught_exception.d.ts +3 -0
  19. package/dist/server/integrations/unhandled_rejection.d.ts +3 -0
  20. package/dist/server/middleware.d.ts +5 -0
  21. package/dist/server/transport.d.ts +10 -0
  22. package/dist/server/{types/server/util.d.ts → util.d.ts} +3 -2
  23. package/honeybadger.d.ts +2 -2
  24. package/package.json +28 -40
  25. package/dist/browser/types/browser/integrations/breadcrumbs.d.ts +0 -2
  26. package/dist/browser/types/browser/integrations/event_listeners.d.ts +0 -2
  27. package/dist/browser/types/browser/integrations/onerror.d.ts +0 -3
  28. package/dist/browser/types/browser/integrations/onunhandledrejection.d.ts +0 -2
  29. package/dist/browser/types/browser/integrations/timers.d.ts +0 -2
  30. package/dist/browser/types/browser/transport.d.ts +0 -7
  31. package/dist/browser/types/browser.d.ts +0 -12
  32. package/dist/browser/types/core/client.d.ts +0 -37
  33. package/dist/browser/types/core/store.d.ts +0 -7
  34. package/dist/browser/types/core/types.d.ts +0 -160
  35. package/dist/browser/types/core/util.d.ts +0 -32
  36. package/dist/browser/types/server/async_store.d.ts +0 -5
  37. package/dist/browser/types/server/aws_lambda.d.ts +0 -10
  38. package/dist/browser/types/server/integrations/uncaught_exception.d.ts +0 -2
  39. package/dist/browser/types/server/integrations/unhandled_rejection.d.ts +0 -2
  40. package/dist/browser/types/server/middleware.d.ts +0 -4
  41. package/dist/browser/types/server/transport.d.ts +0 -9
  42. package/dist/browser/types/server/util.d.ts +0 -9
  43. package/dist/browser/types/server.d.ts +0 -17
  44. package/dist/server/types/browser/integrations/breadcrumbs.d.ts +0 -2
  45. package/dist/server/types/browser/integrations/event_listeners.d.ts +0 -2
  46. package/dist/server/types/browser/integrations/onerror.d.ts +0 -3
  47. package/dist/server/types/browser/integrations/onunhandledrejection.d.ts +0 -2
  48. package/dist/server/types/browser/integrations/timers.d.ts +0 -2
  49. package/dist/server/types/browser/transport.d.ts +0 -7
  50. package/dist/server/types/browser/util.d.ts +0 -18
  51. package/dist/server/types/browser.d.ts +0 -12
  52. package/dist/server/types/core/client.d.ts +0 -37
  53. package/dist/server/types/core/store.d.ts +0 -7
  54. package/dist/server/types/core/types.d.ts +0 -160
  55. package/dist/server/types/core/util.d.ts +0 -32
  56. package/dist/server/types/server/async_store.d.ts +0 -5
  57. package/dist/server/types/server/integrations/uncaught_exception.d.ts +0 -2
  58. package/dist/server/types/server/integrations/unhandled_rejection.d.ts +0 -2
  59. package/dist/server/types/server/middleware.d.ts +0 -4
  60. package/dist/server/types/server/transport.d.ts +0 -9
  61. package/dist/server/types/server.d.ts +0 -17
@@ -1,1743 +1,1840 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
- typeof define === 'function' && define.amd ? define(factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Honeybadger = factory());
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
+ typeof define === 'function' && define.amd ? define(factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Honeybadger = factory());
5
5
  })(this, (function () { 'use strict';
6
6
 
7
- /*! *****************************************************************************
8
- Copyright (c) Microsoft Corporation.
9
-
10
- Permission to use, copy, modify, and/or distribute this software for any
11
- purpose with or without fee is hereby granted.
12
-
13
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
- PERFORMANCE OF THIS SOFTWARE.
20
- ***************************************************************************** */
21
- /* global Reflect, Promise */
22
-
23
- var extendStatics = function(d, b) {
24
- extendStatics = Object.setPrototypeOf ||
25
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
27
- return extendStatics(d, b);
28
- };
29
-
30
- function __extends(d, b) {
31
- if (typeof b !== "function" && b !== null)
32
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
33
- extendStatics(d, b);
34
- function __() { this.constructor = d; }
35
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
36
- }
37
-
38
- var __assign = function() {
39
- __assign = Object.assign || function __assign(t) {
40
- for (var s, i = 1, n = arguments.length; i < n; i++) {
41
- s = arguments[i];
42
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
43
- }
44
- return t;
45
- };
46
- return __assign.apply(this, arguments);
47
- };
48
-
49
- function __awaiter(thisArg, _arguments, P, generator) {
50
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
51
- return new (P || (P = Promise))(function (resolve, reject) {
52
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
53
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
54
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
55
- step((generator = generator.apply(thisArg, _arguments || [])).next());
56
- });
57
- }
58
-
59
- function __generator(thisArg, body) {
60
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
61
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
62
- function verb(n) { return function (v) { return step([n, v]); }; }
63
- function step(op) {
64
- if (f) throw new TypeError("Generator is already executing.");
65
- while (_) try {
66
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
67
- if (y = 0, t) op = [op[0] & 2, t.value];
68
- switch (op[0]) {
69
- case 0: case 1: t = op; break;
70
- case 4: _.label++; return { value: op[1], done: false };
71
- case 5: _.label++; y = op[1]; op = [0]; continue;
72
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
73
- default:
74
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
75
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
76
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
77
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
78
- if (t[2]) _.ops.pop();
79
- _.trys.pop(); continue;
80
- }
81
- op = body.call(thisArg, _);
82
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
83
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
84
- }
85
- }
7
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
86
8
 
87
- var UNKNOWN_FUNCTION = '<unknown>';
88
- /**
89
- * This parses the different stack traces and puts them into one format
90
- * This borrows heavily from TraceKit (https://github.com/csnover/TraceKit)
91
- */
9
+ function getAugmentedNamespace(n) {
10
+ var f = n.default;
11
+ if (typeof f == "function") {
12
+ var a = function () {
13
+ return f.apply(this, arguments);
14
+ };
15
+ a.prototype = f.prototype;
16
+ } else a = {};
17
+ Object.defineProperty(a, '__esModule', {value: true});
18
+ Object.keys(n).forEach(function (k) {
19
+ var d = Object.getOwnPropertyDescriptor(n, k);
20
+ Object.defineProperty(a, k, d.get ? d : {
21
+ enumerable: true,
22
+ get: function () {
23
+ return n[k];
24
+ }
25
+ });
26
+ });
27
+ return a;
28
+ }
92
29
 
93
- function parse(stackString) {
94
- var lines = stackString.split('\n');
95
- return lines.reduce(function (stack, line) {
96
- var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
30
+ var browser = {};
97
31
 
98
- if (parseResult) {
99
- stack.push(parseResult);
100
- }
32
+ var src = {};
101
33
 
102
- return stack;
103
- }, []);
104
- }
105
- var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
106
- var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
34
+ var client = {};
107
35
 
108
- function parseChrome(line) {
109
- var parts = chromeRe.exec(line);
36
+ var util$1 = {};
110
37
 
111
- if (!parts) {
112
- return null;
113
- }
38
+ var UNKNOWN_FUNCTION = '<unknown>';
39
+ /**
40
+ * This parses the different stack traces and puts them into one format
41
+ * This borrows heavily from TraceKit (https://github.com/csnover/TraceKit)
42
+ */
114
43
 
115
- var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line
44
+ function parse(stackString) {
45
+ var lines = stackString.split('\n');
46
+ return lines.reduce(function (stack, line) {
47
+ var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
116
48
 
117
- var isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line
49
+ if (parseResult) {
50
+ stack.push(parseResult);
51
+ }
118
52
 
119
- var submatch = chromeEvalRe.exec(parts[2]);
53
+ return stack;
54
+ }, []);
55
+ }
56
+ var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
57
+ var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
120
58
 
121
- if (isEval && submatch != null) {
122
- // throw out eval line/column and use top-most line/column number
123
- parts[2] = submatch[1]; // url
59
+ function parseChrome(line) {
60
+ var parts = chromeRe.exec(line);
124
61
 
125
- parts[3] = submatch[2]; // line
62
+ if (!parts) {
63
+ return null;
64
+ }
126
65
 
127
- parts[4] = submatch[3]; // column
128
- }
66
+ var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line
129
67
 
130
- return {
131
- file: !isNative ? parts[2] : null,
132
- methodName: parts[1] || UNKNOWN_FUNCTION,
133
- arguments: isNative ? [parts[2]] : [],
134
- lineNumber: parts[3] ? +parts[3] : null,
135
- column: parts[4] ? +parts[4] : null
136
- };
137
- }
68
+ var isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line
138
69
 
139
- var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
70
+ var submatch = chromeEvalRe.exec(parts[2]);
140
71
 
141
- function parseWinjs(line) {
142
- var parts = winjsRe.exec(line);
72
+ if (isEval && submatch != null) {
73
+ // throw out eval line/column and use top-most line/column number
74
+ parts[2] = submatch[1]; // url
143
75
 
144
- if (!parts) {
145
- return null;
146
- }
76
+ parts[3] = submatch[2]; // line
147
77
 
148
- return {
149
- file: parts[2],
150
- methodName: parts[1] || UNKNOWN_FUNCTION,
151
- arguments: [],
152
- lineNumber: +parts[3],
153
- column: parts[4] ? +parts[4] : null
154
- };
155
- }
78
+ parts[4] = submatch[3]; // column
79
+ }
156
80
 
157
- var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
158
- var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
81
+ return {
82
+ file: !isNative ? parts[2] : null,
83
+ methodName: parts[1] || UNKNOWN_FUNCTION,
84
+ arguments: isNative ? [parts[2]] : [],
85
+ lineNumber: parts[3] ? +parts[3] : null,
86
+ column: parts[4] ? +parts[4] : null
87
+ };
88
+ }
159
89
 
160
- function parseGecko(line) {
161
- var parts = geckoRe.exec(line);
90
+ var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
162
91
 
163
- if (!parts) {
164
- return null;
165
- }
92
+ function parseWinjs(line) {
93
+ var parts = winjsRe.exec(line);
166
94
 
167
- var isEval = parts[3] && parts[3].indexOf(' > eval') > -1;
168
- var submatch = geckoEvalRe.exec(parts[3]);
95
+ if (!parts) {
96
+ return null;
97
+ }
169
98
 
170
- if (isEval && submatch != null) {
171
- // throw out eval line/column and use top-most line number
172
- parts[3] = submatch[1];
173
- parts[4] = submatch[2];
174
- parts[5] = null; // no column when eval
175
- }
99
+ return {
100
+ file: parts[2],
101
+ methodName: parts[1] || UNKNOWN_FUNCTION,
102
+ arguments: [],
103
+ lineNumber: +parts[3],
104
+ column: parts[4] ? +parts[4] : null
105
+ };
106
+ }
176
107
 
177
- return {
178
- file: parts[3],
179
- methodName: parts[1] || UNKNOWN_FUNCTION,
180
- arguments: parts[2] ? parts[2].split(',') : [],
181
- lineNumber: parts[4] ? +parts[4] : null,
182
- column: parts[5] ? +parts[5] : null
183
- };
184
- }
108
+ var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
109
+ var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
185
110
 
186
- var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
111
+ function parseGecko(line) {
112
+ var parts = geckoRe.exec(line);
187
113
 
188
- function parseJSC(line) {
189
- var parts = javaScriptCoreRe.exec(line);
114
+ if (!parts) {
115
+ return null;
116
+ }
190
117
 
191
- if (!parts) {
192
- return null;
193
- }
118
+ var isEval = parts[3] && parts[3].indexOf(' > eval') > -1;
119
+ var submatch = geckoEvalRe.exec(parts[3]);
194
120
 
195
- return {
196
- file: parts[3],
197
- methodName: parts[1] || UNKNOWN_FUNCTION,
198
- arguments: [],
199
- lineNumber: +parts[4],
200
- column: parts[5] ? +parts[5] : null
201
- };
202
- }
121
+ if (isEval && submatch != null) {
122
+ // throw out eval line/column and use top-most line number
123
+ parts[3] = submatch[1];
124
+ parts[4] = submatch[2];
125
+ parts[5] = null; // no column when eval
126
+ }
203
127
 
204
- var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
128
+ return {
129
+ file: parts[3],
130
+ methodName: parts[1] || UNKNOWN_FUNCTION,
131
+ arguments: parts[2] ? parts[2].split(',') : [],
132
+ lineNumber: parts[4] ? +parts[4] : null,
133
+ column: parts[5] ? +parts[5] : null
134
+ };
135
+ }
205
136
 
206
- function parseNode(line) {
207
- var parts = nodeRe.exec(line);
137
+ var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
208
138
 
209
- if (!parts) {
210
- return null;
211
- }
139
+ function parseJSC(line) {
140
+ var parts = javaScriptCoreRe.exec(line);
212
141
 
213
- return {
214
- file: parts[2],
215
- methodName: parts[1] || UNKNOWN_FUNCTION,
216
- arguments: [],
217
- lineNumber: +parts[3],
218
- column: parts[4] ? +parts[4] : null
219
- };
220
- }
142
+ if (!parts) {
143
+ return null;
144
+ }
221
145
 
222
- function merge(obj1, obj2) {
223
- var result = {};
224
- for (var k in obj1) {
225
- result[k] = obj1[k];
226
- }
227
- for (var k in obj2) {
228
- result[k] = obj2[k];
229
- }
230
- return result;
231
- }
232
- function mergeNotice(notice1, notice2) {
233
- var result = merge(notice1, notice2);
234
- if (notice1.context && notice2.context) {
235
- result.context = merge(notice1.context, notice2.context);
236
- }
237
- return result;
238
- }
239
- function objectIsEmpty(obj) {
240
- for (var k in obj) {
241
- if (Object.prototype.hasOwnProperty.call(obj, k)) {
242
- return false;
243
- }
244
- }
245
- return true;
246
- }
247
- function objectIsExtensible(obj) {
248
- if (typeof Object.isExtensible !== 'function') {
249
- return true;
250
- }
251
- return Object.isExtensible(obj);
252
- }
253
- function makeBacktrace(stack, shift) {
254
- if (shift === void 0) { shift = 0; }
255
- try {
256
- var backtrace = parse(stack)
257
- .map(function (line) {
258
- return {
259
- file: line.file,
260
- method: line.methodName,
261
- number: line.lineNumber,
262
- column: line.column
263
- };
264
- });
265
- backtrace.splice(0, shift);
266
- return backtrace;
267
- }
268
- catch (_err) {
269
- // TODO: log error
270
- return [];
271
- }
272
- }
273
- function getSourceForBacktrace(backtrace, getSourceFileHandler) {
274
- return __awaiter(this, void 0, void 0, function () {
275
- var result, index, trace, fileContent;
276
- return __generator(this, function (_a) {
277
- switch (_a.label) {
278
- case 0:
279
- result = [];
280
- if (!getSourceFileHandler || !backtrace || !backtrace.length) {
281
- return [2 /*return*/, result];
282
- }
283
- index = 0;
284
- _a.label = 1;
285
- case 1:
286
- if (!backtrace.length) return [3 /*break*/, 3];
287
- trace = backtrace.splice(0)[index];
288
- return [4 /*yield*/, getSourceFileHandler(trace.file)];
289
- case 2:
290
- fileContent = _a.sent();
291
- result[index] = getSourceCodeSnippet(fileContent, trace.number);
292
- index++;
293
- return [3 /*break*/, 1];
294
- case 3: return [2 /*return*/, result];
295
- }
296
- });
297
- });
298
- }
299
- function runBeforeNotifyHandlers(notice, handlers) {
300
- var result = true;
301
- for (var i = 0, len = handlers.length; i < len; i++) {
302
- var handler = handlers[i];
303
- if (handler(notice) === false) {
304
- result = false;
305
- }
306
- }
307
- return result;
308
- }
309
- function runAfterNotifyHandlers(notice, handlers, error) {
310
- if (notice && notice.afterNotify) {
311
- notice.afterNotify(error, notice);
312
- }
313
- for (var i = 0, len = handlers.length; i < len; i++) {
314
- handlers[i](error, notice);
315
- }
316
- return true;
317
- }
318
- // Returns a new object with properties from other object.
319
- function shallowClone(obj) {
320
- if (typeof (obj) !== 'object' || obj === null) {
321
- return {};
322
- }
323
- var result = {};
324
- for (var k in obj) {
325
- result[k] = obj[k];
326
- }
327
- return result;
328
- }
329
- function sanitize(obj, maxDepth) {
330
- if (maxDepth === void 0) { maxDepth = 8; }
331
- var seenObjects = [];
332
- function seen(obj) {
333
- if (!obj || typeof (obj) !== 'object') {
334
- return false;
335
- }
336
- for (var i = 0; i < seenObjects.length; i++) {
337
- var value = seenObjects[i];
338
- if (value === obj) {
339
- return true;
340
- }
341
- }
342
- seenObjects.push(obj);
343
- return false;
344
- }
345
- function canSerialize(obj) {
346
- var typeOfObj = typeof obj;
347
- // Functions are TMI
348
- if (/function/.test(typeOfObj)) {
349
- // Let special toJSON method pass as it's used by JSON.stringify (#722)
350
- return obj.name === 'toJSON';
351
- }
352
- // Symbols can't convert to strings.
353
- if (/symbol/.test(typeOfObj)) {
354
- return false;
355
- }
356
- if (obj === null) {
357
- return false;
358
- }
359
- // No prototype, likely created with `Object.create(null)`.
360
- if (typeof obj === 'object' && typeof obj.hasOwnProperty === 'undefined') {
361
- return false;
362
- }
363
- return true;
364
- }
365
- function serialize(obj, depth) {
366
- if (depth === void 0) { depth = 0; }
367
- if (depth >= maxDepth) {
368
- return '[DEPTH]';
369
- }
370
- // Inspect invalid types
371
- if (!canSerialize(obj)) {
372
- return Object.prototype.toString.call(obj);
373
- }
374
- // Halt circular references
375
- if (seen(obj)) {
376
- return '[RECURSION]';
377
- }
378
- // Serialize inside arrays
379
- if (Array.isArray(obj)) {
380
- return obj.map(function (o) { return safeSerialize(o, depth + 1); });
381
- }
382
- // Serialize inside objects
383
- if (typeof (obj) === 'object') {
384
- var ret = {};
385
- for (var k in obj) {
386
- var v = obj[k];
387
- if (Object.prototype.hasOwnProperty.call(obj, k) && (k != null) && (v != null)) {
388
- ret[k] = safeSerialize(v, depth + 1);
389
- }
390
- }
391
- return ret;
392
- }
393
- // Return everything else untouched
394
- return obj;
395
- }
396
- function safeSerialize(obj, depth) {
397
- if (depth === void 0) { depth = 0; }
398
- try {
399
- return serialize(obj, depth);
400
- }
401
- catch (e) {
402
- return "[ERROR] ".concat(e);
403
- }
404
- }
405
- return safeSerialize(obj);
406
- }
407
- function logger(client) {
408
- var log = function (method) {
409
- return function () {
410
- var _a;
411
- var args = [];
412
- for (var _i = 0; _i < arguments.length; _i++) {
413
- args[_i] = arguments[_i];
414
- }
415
- if (method === 'debug') {
416
- if (!client.config.debug) {
417
- return;
418
- }
419
- // Log at default level so that you don't need to also enable verbose
420
- // logging in Chrome.
421
- method = 'log';
422
- }
423
- args.unshift('[Honeybadger]');
424
- (_a = client.config.logger)[method].apply(_a, args);
425
- };
426
- };
427
- return {
428
- log: log('log'),
429
- info: log('info'),
430
- debug: log('debug'),
431
- warn: log('warn'),
432
- error: log('error')
433
- };
434
- }
435
- /**
436
- * Converts any object into a notice object (which at minimum has the same
437
- * properties as Error, but supports additional Honeybadger properties.)
438
- */
439
- function makeNotice(thing) {
440
- var notice;
441
- if (!thing) {
442
- notice = {};
443
- }
444
- else if (thing instanceof Error || Object.prototype.toString.call(thing) === '[object Error]') {
445
- var e = thing;
446
- notice = merge(thing, { name: e.name, message: e.message, stack: e.stack });
447
- }
448
- else if (typeof thing === 'object') {
449
- notice = shallowClone(thing);
450
- }
451
- else {
452
- var m = String(thing);
453
- notice = { message: m };
454
- }
455
- return notice;
456
- }
457
- /**
458
- * Instrument an existing function inside an object (usually global).
459
- * @param {!Object} object
460
- * @param {!String} name
461
- * @param {!Function} replacement
462
- */
463
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
464
- function instrument(object, name, replacement) {
465
- if (!object || !name || !replacement || !(name in object)) {
466
- return;
467
- }
468
- var original = object[name];
469
- while (original && original.__hb_original) {
470
- original = original.__hb_original;
471
- }
472
- try {
473
- object[name] = replacement(original);
474
- object[name].__hb_original = original;
475
- }
476
- catch (_e) {
477
- // Ignores errors like this one:
478
- // Error: TypeError: Cannot set property onunhandledrejection of [object Object] which has only a getter
479
- // User-Agent: Mozilla/5.0 (Linux; Android 10; SAMSUNG SM-G960F) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/12.1 Chrome/79.0.3945.136 Mobile Safari/537.36
480
- }
481
- }
482
- function endpoint(base, path) {
483
- var endpoint = base.trim().replace(/\/$/, '');
484
- path = path.trim().replace(/(^\/|\/$)/g, '');
485
- return "".concat(endpoint, "/").concat(path);
486
- }
487
- function generateStackTrace() {
488
- try {
489
- throw new Error('');
490
- }
491
- catch (e) {
492
- if (e.stack) {
493
- return e.stack;
494
- }
495
- }
496
- var maxStackSize = 10;
497
- var stack = [];
498
- var curr = arguments.callee;
499
- while (curr && stack.length < maxStackSize) {
500
- if (/function(?:\s+([\w$]+))+\s*\(/.test(curr.toString())) {
501
- stack.push(RegExp.$1 || '<anonymous>');
502
- }
503
- else {
504
- stack.push('<anonymous>');
505
- }
506
- try {
507
- curr = curr.caller;
508
- }
509
- catch (e) {
510
- break;
511
- }
512
- }
513
- return stack.join('\n');
514
- }
515
- function filter(obj, filters) {
516
- if (!is('Object', obj)) {
517
- return;
518
- }
519
- if (!is('Array', filters)) {
520
- filters = [];
521
- }
522
- var seen = [];
523
- function filter(obj) {
524
- var k, newObj;
525
- if (is('Object', obj) || is('Array', obj)) {
526
- if (seen.indexOf(obj) !== -1) {
527
- return '[CIRCULAR DATA STRUCTURE]';
528
- }
529
- seen.push(obj);
530
- }
531
- if (is('Object', obj)) {
532
- newObj = {};
533
- for (k in obj) {
534
- if (filterMatch(k, filters)) {
535
- newObj[k] = '[FILTERED]';
536
- }
537
- else {
538
- newObj[k] = filter(obj[k]);
539
- }
540
- }
541
- return newObj;
542
- }
543
- if (is('Array', obj)) {
544
- return obj.map(function (v) {
545
- return filter(v);
546
- });
547
- }
548
- if (is('Function', obj)) {
549
- return '[FUNC]';
550
- }
551
- return obj;
552
- }
553
- return filter(obj);
554
- }
555
- function filterMatch(key, filters) {
556
- for (var i = 0; i < filters.length; i++) {
557
- if (key.toLowerCase().indexOf(filters[i].toLowerCase()) !== -1) {
558
- return true;
559
- }
560
- }
561
- return false;
562
- }
563
- function is(type, obj) {
564
- var klass = Object.prototype.toString.call(obj).slice(8, -1);
565
- return obj !== undefined && obj !== null && klass === type;
566
- }
567
- function filterUrl(url, filters) {
568
- if (!filters) {
569
- return url;
570
- }
571
- if (typeof url !== 'string') {
572
- return url;
573
- }
574
- var query = url.split(/\?/, 2)[1];
575
- if (!query) {
576
- return url;
577
- }
578
- var result = url;
579
- query.split(/[&]\s?/).forEach(function (pair) {
580
- var _a = pair.split('=', 2), key = _a[0], value = _a[1];
581
- if (filterMatch(key, filters)) {
582
- result = result.replace("".concat(key, "=").concat(value), "".concat(key, "=[FILTERED]"));
583
- }
584
- });
585
- return result;
586
- }
587
- function formatCGIData(vars, prefix) {
588
- if (prefix === void 0) { prefix = ''; }
589
- var formattedVars = {};
590
- Object.keys(vars).forEach(function (key) {
591
- var formattedKey = prefix + key.replace(/\W/g, '_').toUpperCase();
592
- formattedVars[formattedKey] = vars[key];
593
- });
594
- return formattedVars;
595
- }
596
- function getSourceCodeSnippet(fileData, lineNumber, sourceRadius) {
597
- if (sourceRadius === void 0) { sourceRadius = 2; }
598
- if (!fileData) {
599
- return null;
600
- }
601
- var lines = fileData.split('\n');
602
- // add one empty line because array index starts from 0, but error line number is counted from 1
603
- lines.unshift('');
604
- var start = lineNumber - sourceRadius;
605
- var end = lineNumber + sourceRadius;
606
- var result = {};
607
- for (var i = start; i <= end; i++) {
608
- var line = lines[i];
609
- if (typeof line === 'string') {
610
- result[i] = line;
611
- }
612
- }
613
- return result;
614
- }
615
- function isBrowserConfig(config) {
616
- return config.async !== undefined;
617
- }
146
+ return {
147
+ file: parts[3],
148
+ methodName: parts[1] || UNKNOWN_FUNCTION,
149
+ arguments: [],
150
+ lineNumber: +parts[4],
151
+ column: parts[5] ? +parts[5] : null
152
+ };
153
+ }
618
154
 
619
- var GlobalStore = /** @class */ (function () {
620
- function GlobalStore(store) {
621
- this.store = store;
622
- }
623
- GlobalStore.prototype.getStore = function () {
624
- return this.store;
625
- };
626
- GlobalStore.prototype.run = function (store, callback) {
627
- var args = [];
628
- for (var _i = 2; _i < arguments.length; _i++) {
629
- args[_i - 2] = arguments[_i];
630
- }
631
- this.store = store;
632
- return callback.apply(void 0, args);
633
- };
634
- return GlobalStore;
635
- }());
155
+ var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
636
156
 
637
- var notifier = {
638
- name: 'honeybadger-js',
639
- url: 'https://github.com/honeybadger-io/honeybadger-js',
640
- version: '4.0.3'
641
- };
642
- // Split at commas and spaces
643
- var TAG_SEPARATOR = /,|\s+/;
644
- // Checks for non-blank characters
645
- var NOT_BLANK = /\S/;
646
- var Client = /** @class */ (function () {
647
- function Client(opts, transport) {
648
- if (opts === void 0) { opts = {}; }
649
- this.__pluginsExecuted = false;
650
- this.__store = null;
651
- this.__beforeNotifyHandlers = [];
652
- this.__afterNotifyHandlers = [];
653
- this.config = __assign({ apiKey: null, endpoint: 'https://api.honeybadger.io', environment: null, hostname: null, projectRoot: null, component: null, action: null, revision: null, reportData: null, breadcrumbsEnabled: true, maxBreadcrumbs: 40, maxObjectDepth: 8, logger: console, developmentEnvironments: ['dev', 'development', 'test'], debug: false, tags: null, enableUncaught: true, enableUnhandledRejection: true, afterUncaught: function () { return true; }, filters: ['creditcard', 'password'], __plugins: [] }, opts);
654
- // First, we go with the global (shared) store.
655
- // Webserver middleware can then switch to the AsyncStore for async context tracking.
656
- this.__store = new GlobalStore({ context: {}, breadcrumbs: [] });
657
- this.__transport = transport;
658
- this.logger = logger(this);
659
- }
660
- Client.prototype.getVersion = function () {
661
- return notifier.version;
662
- };
663
- Client.prototype.configure = function (opts) {
664
- var _this = this;
665
- if (opts === void 0) { opts = {}; }
666
- for (var k in opts) {
667
- this.config[k] = opts[k];
668
- }
669
- if (!this.__pluginsExecuted) {
670
- this.__pluginsExecuted = true;
671
- this.config.__plugins.forEach(function (plugin) { return plugin.load(_this); });
672
- }
673
- return this;
674
- };
675
- /** @internal */
676
- Client.prototype.__setStore = function (store) {
677
- this.__store = store;
678
- };
679
- Client.prototype.beforeNotify = function (handler) {
680
- this.__beforeNotifyHandlers.push(handler);
681
- return this;
682
- };
683
- Client.prototype.afterNotify = function (handler) {
684
- this.__afterNotifyHandlers.push(handler);
685
- return this;
686
- };
687
- Client.prototype.setContext = function (context) {
688
- if (typeof context === 'object') {
689
- var store = this.__store.getStore();
690
- store.context = merge(store.context, context);
691
- }
692
- return this;
693
- };
694
- Client.prototype.resetContext = function (context) {
695
- this.logger.warn('Deprecation warning: `Honeybadger.resetContext()` has been deprecated; please use `Honeybadger.clear()` instead.');
696
- var store = this.__store.getStore();
697
- if (typeof context === 'object' && context !== null) {
698
- store.context = context;
699
- }
700
- else {
701
- store.context = {};
702
- }
703
- return this;
704
- };
705
- Client.prototype.clear = function () {
706
- var store = this.__store.getStore();
707
- store.context = {};
708
- store.breadcrumbs = [];
709
- return this;
710
- };
711
- Client.prototype.notify = function (noticeable, name, extra) {
712
- var _this = this;
713
- if (name === void 0) { name = undefined; }
714
- if (extra === void 0) { extra = undefined; }
715
- var preConditionError = null;
716
- var notice = this.makeNotice(noticeable, name, extra);
717
- if (!notice) {
718
- this.logger.debug('failed to build error report');
719
- preConditionError = new Error('failed to build error report');
720
- }
721
- if (!preConditionError && this.config.reportData === false) {
722
- this.logger.debug('skipping error report: honeybadger.js is disabled', notice);
723
- preConditionError = new Error('honeybadger.js is disabled');
724
- }
725
- if (!preConditionError && this.__developmentMode()) {
726
- this.logger.log('honeybadger.js is in development mode; the following error report will be sent in production.', notice);
727
- preConditionError = new Error('honeybadger.js is in development mode');
728
- }
729
- if (!preConditionError && !this.config.apiKey) {
730
- this.logger.warn('could not send error report: no API key has been configured', notice);
731
- preConditionError = new Error('missing API key');
732
- }
733
- // we need to have the source file data before the beforeNotifyHandlers,
734
- // in case they modify them
735
- var sourceCodeData = notice && notice.backtrace ? notice.backtrace.map(function (trace) { return shallowClone(trace); }) : null;
736
- var beforeNotifyResult = runBeforeNotifyHandlers(notice, this.__beforeNotifyHandlers);
737
- if (!preConditionError && !beforeNotifyResult) {
738
- this.logger.debug('skipping error report: beforeNotify handlers returned false', notice);
739
- preConditionError = new Error('beforeNotify handlers returned false');
740
- }
741
- if (preConditionError) {
742
- runAfterNotifyHandlers(notice, this.__afterNotifyHandlers, preConditionError);
743
- return false;
744
- }
745
- this.addBreadcrumb('Honeybadger Notice', {
746
- category: 'notice',
747
- metadata: {
748
- message: notice.message,
749
- name: notice.name,
750
- stack: notice.stack
751
- }
752
- });
753
- var breadcrumbs = this.__getStoreContentsOrDefault().breadcrumbs;
754
- notice.__breadcrumbs = this.config.breadcrumbsEnabled ? breadcrumbs.slice() : [];
755
- getSourceForBacktrace(sourceCodeData, this.__getSourceFileHandler)
756
- .then(function (sourcePerTrace) {
757
- sourcePerTrace.forEach(function (source, index) {
758
- notice.backtrace[index].source = source;
759
- });
760
- var payload = _this.__buildPayload(notice);
761
- _this.__transport
762
- .send({
763
- headers: {
764
- 'X-API-Key': _this.config.apiKey,
765
- 'Content-Type': 'application/json',
766
- 'Accept': 'text/json, application/json'
767
- },
768
- method: 'POST',
769
- endpoint: endpoint(_this.config.endpoint, '/v1/notices/js'),
770
- maxObjectDepth: _this.config.maxObjectDepth,
771
- logger: _this.logger,
772
- async: isBrowserConfig(_this.config) ? _this.config.async : undefined,
773
- }, payload)
774
- .then(function (res) {
775
- if (res.statusCode !== 201) {
776
- runAfterNotifyHandlers(notice, _this.__afterNotifyHandlers, new Error("Bad HTTP response: ".concat(res.statusCode)));
777
- _this.logger.warn("Error report failed: unknown response from server. code=".concat(res.statusCode));
778
- return;
779
- }
780
- var uuid = JSON.parse(res.body).id;
781
- runAfterNotifyHandlers(merge(notice, {
782
- id: uuid
783
- }), _this.__afterNotifyHandlers);
784
- _this.logger.info("Error report sent \u26A1 https://app.honeybadger.io/notice/".concat(uuid));
785
- })
786
- .catch(function (err) {
787
- _this.logger.error('Error report failed: an unknown error occurred.', "message=".concat(err.message));
788
- runAfterNotifyHandlers(notice, _this.__afterNotifyHandlers, err);
789
- });
790
- });
791
- return true;
792
- };
793
- /**
794
- * An async version of {@link notify} that resolves only after the notice has been reported to Honeybadger.
795
- * Implemented using the {@link afterNotify} hook.
796
- * Rejects if for any reason the report failed to be reported.
797
- * Useful in serverless environments (AWS Lambda).
798
- */
799
- Client.prototype.notifyAsync = function (noticeable, name, extra) {
800
- var _this = this;
801
- if (name === void 0) { name = undefined; }
802
- if (extra === void 0) { extra = undefined; }
803
- return new Promise(function (resolve, reject) {
804
- var applyAfterNotify = function (partialNotice) {
805
- var originalAfterNotify = partialNotice.afterNotify;
806
- partialNotice.afterNotify = function (err) {
807
- originalAfterNotify === null || originalAfterNotify === void 0 ? void 0 : originalAfterNotify.call(_this, err);
808
- if (err) {
809
- return reject(err);
810
- }
811
- resolve();
812
- };
813
- };
814
- // We have to respect any afterNotify hooks that come from the arguments
815
- var objectToOverride;
816
- if (noticeable.afterNotify) {
817
- objectToOverride = noticeable;
818
- }
819
- else if (name && name.afterNotify) {
820
- objectToOverride = name;
821
- }
822
- else if (extra && extra.afterNotify) {
823
- objectToOverride = extra;
824
- }
825
- else if (name && typeof name === 'object') {
826
- objectToOverride = name;
827
- }
828
- else if (extra) {
829
- objectToOverride = extra;
830
- }
831
- else {
832
- objectToOverride = name = {};
833
- }
834
- applyAfterNotify(objectToOverride);
835
- _this.notify(noticeable, name, extra);
836
- });
837
- };
838
- Client.prototype.makeNotice = function (noticeable, name, extra) {
839
- if (name === void 0) { name = undefined; }
840
- if (extra === void 0) { extra = undefined; }
841
- var notice = makeNotice(noticeable);
842
- if (name && !(typeof name === 'object')) {
843
- var n = String(name);
844
- name = { name: n };
845
- }
846
- if (name) {
847
- notice = mergeNotice(notice, name);
848
- }
849
- if (typeof extra === 'object' && extra !== null) {
850
- notice = mergeNotice(notice, extra);
851
- }
852
- if (objectIsEmpty(notice)) {
853
- return null;
854
- }
855
- var context = this.__getStoreContentsOrDefault().context;
856
- var noticeTags = this.__constructTags(notice.tags);
857
- var contextTags = this.__constructTags(context['tags']);
858
- var configTags = this.__constructTags(this.config.tags);
859
- // Turning into a Set will remove duplicates
860
- var tags = noticeTags.concat(contextTags).concat(configTags);
861
- var uniqueTags = tags.filter(function (item, index) { return tags.indexOf(item) === index; });
862
- notice = merge(notice, {
863
- name: notice.name || 'Error',
864
- context: merge(context, notice.context),
865
- projectRoot: notice.projectRoot || this.config.projectRoot,
866
- environment: notice.environment || this.config.environment,
867
- component: notice.component || this.config.component,
868
- action: notice.action || this.config.action,
869
- revision: notice.revision || this.config.revision,
870
- tags: uniqueTags
871
- });
872
- var backtraceShift = 0;
873
- if (typeof notice.stack !== 'string' || !notice.stack.trim()) {
874
- notice.stack = generateStackTrace();
875
- backtraceShift = 2;
876
- }
877
- notice.backtrace = makeBacktrace(notice.stack, backtraceShift);
878
- return notice;
879
- };
880
- Client.prototype.addBreadcrumb = function (message, opts) {
881
- if (!this.config.breadcrumbsEnabled) {
882
- return;
883
- }
884
- opts = opts || {};
885
- var metadata = shallowClone(opts.metadata);
886
- var category = opts.category || 'custom';
887
- var timestamp = new Date().toISOString();
888
- var store = this.__store.getStore();
889
- var breadcrumbs = store.breadcrumbs;
890
- breadcrumbs.push({
891
- category: category,
892
- message: message,
893
- metadata: metadata,
894
- timestamp: timestamp
895
- });
896
- var limit = this.config.maxBreadcrumbs;
897
- if (breadcrumbs.length > limit) {
898
- breadcrumbs = breadcrumbs.slice(breadcrumbs.length - limit);
899
- }
900
- store.breadcrumbs = breadcrumbs;
901
- return this;
902
- };
903
- Client.prototype.__developmentMode = function () {
904
- if (this.config.reportData === true) {
905
- return false;
906
- }
907
- return (this.config.environment && this.config.developmentEnvironments.includes(this.config.environment));
908
- };
909
- Client.prototype.__buildPayload = function (notice) {
910
- var headers = filter(notice.headers, this.config.filters) || {};
911
- var cgiData = filter(__assign(__assign({}, notice.cgiData), formatCGIData(headers, 'HTTP_')), this.config.filters);
912
- return {
913
- notifier: notifier,
914
- breadcrumbs: {
915
- enabled: !!this.config.breadcrumbsEnabled,
916
- trail: notice.__breadcrumbs || []
917
- },
918
- error: {
919
- class: notice.name,
920
- message: notice.message,
921
- backtrace: notice.backtrace,
922
- fingerprint: notice.fingerprint,
923
- tags: notice.tags
924
- },
925
- request: {
926
- url: filterUrl(notice.url, this.config.filters),
927
- component: notice.component,
928
- action: notice.action,
929
- context: notice.context,
930
- cgi_data: cgiData,
931
- params: filter(notice.params, this.config.filters) || {},
932
- session: filter(notice.session, this.config.filters) || {}
933
- },
934
- server: {
935
- project_root: notice.projectRoot,
936
- environment_name: notice.environment,
937
- revision: notice.revision,
938
- hostname: this.config.hostname,
939
- time: new Date().toUTCString()
940
- },
941
- details: notice.details || {}
942
- };
943
- };
944
- Client.prototype.__constructTags = function (tags) {
945
- if (!tags) {
946
- return [];
947
- }
948
- return tags.toString().split(TAG_SEPARATOR).filter(function (tag) { return NOT_BLANK.test(tag); });
949
- };
950
- /**
951
- * For ALS, the store may be uninitialized (if .run()` has not been called).
952
- * This provides an easy way to read the existing store object or fall back to a default.
953
- * Returns *a copy* of the store contents.
954
- * @internal
955
- */
956
- Client.prototype.__getStoreContentsOrDefault = function () {
957
- var existingStoreContents = this.__store.getStore();
958
- var storeContents = existingStoreContents || {};
959
- return __assign({ context: {}, breadcrumbs: [] }, storeContents);
960
- };
961
- return Client;
962
- }());
157
+ function parseNode(line) {
158
+ var parts = nodeRe.exec(line);
963
159
 
964
- /**
965
- * Converts an HTMLElement into a human-readable string.
966
- * @param {!HTMLElement} element
967
- * @return {string}
968
- */
969
- function stringNameOfElement(element) {
970
- if (!element || !element.tagName) {
971
- return '';
972
- }
973
- var name = element.tagName.toLowerCase();
974
- // Ignore the root <html> element in selectors and events.
975
- if (name === 'html') {
976
- return '';
977
- }
978
- if (element.id) {
979
- name += "#".concat(element.id);
980
- }
981
- var stringClassNames = element.getAttribute('class');
982
- if (stringClassNames) {
983
- stringClassNames.split(/\s+/).forEach(function (className) {
984
- name += ".".concat(className);
985
- });
986
- }
987
- ['alt', 'name', 'title', 'type'].forEach(function (attrName) {
988
- var attr = element.getAttribute(attrName);
989
- if (attr) {
990
- name += "[".concat(attrName, "=\"").concat(attr, "\"]");
991
- }
992
- });
993
- var siblings = getSiblings(element);
994
- if (siblings.length > 1) {
995
- name += ":nth-child(".concat(Array.prototype.indexOf.call(siblings, element) + 1, ")");
996
- }
997
- return name;
998
- }
999
- function stringSelectorOfElement(element) {
1000
- var name = stringNameOfElement(element);
1001
- if (element.parentNode && element.parentNode.tagName) {
1002
- var parentName = stringSelectorOfElement(element.parentNode);
1003
- if (parentName.length > 0) {
1004
- return "".concat(parentName, " > ").concat(name);
1005
- }
1006
- }
1007
- return name;
1008
- }
1009
- function stringTextOfElement(element) {
1010
- var text = element.textContent || element.innerText || '';
1011
- if (!text && (element.type === 'submit' || element.type === 'button')) {
1012
- text = element.value;
1013
- }
1014
- return truncate(text.trim(), 300);
1015
- }
1016
- function nativeFetch() {
1017
- if (!window.fetch) {
1018
- return false;
1019
- }
1020
- if (isNative(window.fetch)) {
1021
- return true;
1022
- }
1023
- // If fetch isn't native, it may be wrapped by someone else. Try to get
1024
- // a pristine function from an iframe.
1025
- try {
1026
- var sandbox = document.createElement('iframe');
1027
- sandbox.style.display = 'none';
1028
- document.head.appendChild(sandbox);
1029
- var result = sandbox.contentWindow.fetch && isNative(sandbox.contentWindow.fetch);
1030
- document.head.removeChild(sandbox);
1031
- return result;
1032
- }
1033
- catch (err) {
1034
- if (console && console.warn) {
1035
- console.warn('failed to detect native fetch via iframe: ' + err);
1036
- }
1037
- }
1038
- return false;
1039
- }
1040
- function isNative(func) {
1041
- return func.toString().indexOf('native') !== -1;
1042
- }
1043
- function parseURL(url) {
1044
- // Regexp: https://tools.ietf.org/html/rfc3986#appendix-B
1045
- var match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/) || {};
1046
- return {
1047
- protocol: match[2],
1048
- host: match[4],
1049
- pathname: match[5]
1050
- };
1051
- }
1052
- function localURLPathname(url) {
1053
- var parsed = parseURL(url);
1054
- var parsedDocURL = parseURL(document.URL);
1055
- // URL must be relative
1056
- if (!parsed.host || !parsed.protocol) {
1057
- return parsed.pathname;
1058
- }
1059
- // Same domain
1060
- if (parsed.protocol === parsedDocURL.protocol && parsed.host === parsedDocURL.host) {
1061
- return parsed.pathname;
1062
- }
1063
- // x-domain
1064
- return "".concat(parsed.protocol, "://").concat(parsed.host).concat(parsed.pathname);
1065
- }
1066
- function decodeCookie(string) {
1067
- var result = {};
1068
- string.split(/[;,]\s?/).forEach(function (pair) {
1069
- var _a = pair.split('=', 2), key = _a[0], value = _a[1];
1070
- result[key] = value;
1071
- });
1072
- return result;
1073
- }
1074
- function encodeCookie(object) {
1075
- if (typeof object !== 'object') {
1076
- return undefined;
1077
- }
1078
- var cookies = [];
1079
- for (var k in object) {
1080
- cookies.push(k + '=' + object[k]);
1081
- }
1082
- return cookies.join(';');
1083
- }
1084
- // Helpers
1085
- function getSiblings(element) {
1086
- try {
1087
- var nodes = element.parentNode.childNodes;
1088
- var siblings_1 = [];
1089
- Array.prototype.forEach.call(nodes, function (node) {
1090
- if (node.tagName && node.tagName === element.tagName) {
1091
- siblings_1.push(node);
1092
- }
1093
- });
1094
- return siblings_1;
1095
- }
1096
- catch (e) {
1097
- return [];
1098
- }
1099
- }
1100
- function truncate(string, length) {
1101
- if (string.length > length) {
1102
- string = string.substr(0, length) + '...';
1103
- }
1104
- return string;
1105
- }
1106
- // Used to decide which error handling method to use when wrapping async
1107
- // handlers: try/catch, or `window.onerror`. When available, `window.onerror`
1108
- // will provide more information in modern browsers.
1109
- var preferCatch = (function () {
1110
- var preferCatch = true;
1111
- // IE < 10
1112
- if (!window.atob) {
1113
- preferCatch = false;
1114
- }
1115
- // Modern browsers support the full ErrorEvent API
1116
- // See https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent
1117
- if (window.ErrorEvent) {
1118
- try {
1119
- if ((new window.ErrorEvent('')).colno === 0) {
1120
- preferCatch = false;
1121
- }
1122
- // eslint-disable-next-line no-empty
1123
- }
1124
- catch (_e) { }
1125
- }
1126
- return preferCatch;
1127
- })();
160
+ if (!parts) {
161
+ return null;
162
+ }
1128
163
 
1129
- /* eslint-disable prefer-rest-params */
1130
- var ignoreOnError = 0;
1131
- var currentTimeout;
1132
- function ignoreNextOnError() {
1133
- ignoreOnError += 1;
1134
- clearTimeout(currentTimeout);
1135
- currentTimeout = setTimeout(function () {
1136
- ignoreOnError = 0;
1137
- });
1138
- }
1139
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1140
- function onError(_window) {
1141
- if (_window === void 0) { _window = window; }
1142
- return {
1143
- load: function (client) {
1144
- instrument(_window, 'onerror', function (original) {
1145
- var onerror = function (msg, url, line, col, err) {
1146
- client.logger.debug('window.onerror callback invoked', arguments);
1147
- if (ignoreOnError > 0) {
1148
- client.logger.debug('Ignoring window.onerror (error likely reported earlier)', arguments);
1149
- ignoreOnError -= 1;
1150
- return;
1151
- }
1152
- // See https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onerror#Notes
1153
- if (line === 0 && /Script error\.?/.test(msg)) {
1154
- if (client.config.enableUncaught) {
1155
- // Log only if the user wants to report uncaught errors
1156
- client.logger.warn('Ignoring cross-domain script error: enable CORS to track these types of errors', arguments);
1157
- }
1158
- return;
1159
- }
1160
- var notice = makeNotice(err);
1161
- if (!notice.name) {
1162
- notice.name = 'window.onerror';
1163
- }
1164
- if (!notice.message) {
1165
- notice.message = msg;
1166
- }
1167
- if (!notice.stack) {
1168
- // Simulate v8 stack
1169
- notice.stack = [notice.message, '\n at ? (', url || 'unknown', ':', line || 0, ':', col || 0, ')'].join('');
1170
- }
1171
- client.addBreadcrumb((notice.name === 'window.onerror' || !notice.name) ? 'window.onerror' : "window.onerror: ".concat(notice.name), {
1172
- category: 'error',
1173
- metadata: {
1174
- name: notice.name,
1175
- message: notice.message,
1176
- stack: notice.stack
1177
- }
1178
- });
1179
- if (client.config.enableUncaught) {
1180
- client.notify(notice);
1181
- }
1182
- };
1183
- return function (msg, url, line, col, err) {
1184
- onerror(msg, url, line, col, err);
1185
- if (typeof original === 'function') {
1186
- return original.apply(window, arguments);
1187
- }
1188
- return false;
1189
- };
1190
- });
1191
- }
1192
- };
1193
- }
164
+ return {
165
+ file: parts[2],
166
+ methodName: parts[1] || UNKNOWN_FUNCTION,
167
+ arguments: [],
168
+ lineNumber: +parts[3],
169
+ column: parts[4] ? +parts[4] : null
170
+ };
171
+ }
1194
172
 
1195
- /* eslint-disable prefer-rest-params */
1196
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1197
- function onUnhandledRejection (_window) {
1198
- if (_window === void 0) { _window = window; }
1199
- return {
1200
- load: function (client) {
1201
- if (!client.config.enableUnhandledRejection) {
1202
- return;
1203
- }
1204
- instrument(_window, 'onunhandledrejection', function (original) {
1205
- // See https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event
1206
- function onunhandledrejection(promiseRejectionEvent) {
1207
- var _a;
1208
- client.logger.debug('window.onunhandledrejection callback invoked', arguments);
1209
- if (!client.config.enableUnhandledRejection) {
1210
- return;
1211
- }
1212
- var reason = promiseRejectionEvent.reason;
1213
- if (reason instanceof Error) {
1214
- // simulate v8 stack
1215
- // const fileName = reason.fileName || 'unknown'
1216
- // const lineNumber = reason.lineNumber || 0
1217
- var fileName = 'unknown';
1218
- var lineNumber = 0;
1219
- var stackFallback = "".concat(reason.message, "\n at ? (").concat(fileName, ":").concat(lineNumber, ")");
1220
- var stack = reason.stack || stackFallback;
1221
- var err = {
1222
- name: reason.name,
1223
- message: "UnhandledPromiseRejectionWarning: ".concat(reason),
1224
- stack: stack
1225
- };
1226
- client.addBreadcrumb("window.onunhandledrejection: ".concat(err.name), {
1227
- category: 'error',
1228
- metadata: err
1229
- });
1230
- client.notify(err);
1231
- return;
1232
- }
1233
- var message = typeof reason === 'string' ? reason : ((_a = JSON.stringify(reason)) !== null && _a !== void 0 ? _a : 'Unspecified reason');
1234
- client.notify({
1235
- name: 'window.onunhandledrejection',
1236
- message: "UnhandledPromiseRejectionWarning: ".concat(message)
1237
- });
1238
- }
1239
- return function (promiseRejectionEvent) {
1240
- onunhandledrejection(promiseRejectionEvent);
1241
- if (typeof original === 'function') {
1242
- original.apply(this, arguments);
1243
- }
1244
- };
1245
- });
1246
- }
1247
- };
1248
- }
173
+ var stackTraceParser_esm = /*#__PURE__*/Object.freeze({
174
+ __proto__: null,
175
+ parse: parse
176
+ });
1249
177
 
1250
- /* eslint-disable prefer-rest-params */
1251
- function breadcrumbs (_window) {
1252
- if (_window === void 0) { _window = window; }
1253
- return {
1254
- load: function (client) {
1255
- function breadcrumbsEnabled(type) {
1256
- if (client.config.breadcrumbsEnabled === true) {
1257
- return true;
1258
- }
1259
- if (type) {
1260
- return client.config.breadcrumbsEnabled[type] === true;
1261
- }
1262
- return client.config.breadcrumbsEnabled !== false;
1263
- }
1264
- // Breadcrumbs: instrument console
1265
- (function () {
1266
- if (!breadcrumbsEnabled('console')) {
1267
- return;
1268
- }
1269
- function inspectArray(obj) {
1270
- if (!Array.isArray(obj)) {
1271
- return '';
1272
- }
1273
- return obj.map(function (value) {
1274
- try {
1275
- return String(value);
1276
- }
1277
- catch (e) {
1278
- return '[unknown]';
1279
- }
1280
- }).join(' ');
1281
- }
1282
- ['debug', 'info', 'warn', 'error', 'log'].forEach(function (level) {
1283
- instrument(_window.console, level, function (original) {
1284
- return function () {
1285
- var args = Array.prototype.slice.call(arguments);
1286
- var message = inspectArray(args);
1287
- var opts = {
1288
- category: 'log',
1289
- metadata: {
1290
- level: level,
1291
- arguments: sanitize(args, 3)
1292
- }
1293
- };
1294
- client.addBreadcrumb(message, opts);
1295
- if (typeof original === 'function') {
1296
- Function.prototype.apply.call(original, _window.console, arguments);
1297
- }
1298
- };
1299
- });
1300
- });
1301
- })();
1302
- // Breadcrumbs: instrument click events
1303
- (function () {
1304
- if (!breadcrumbsEnabled('dom')) {
1305
- return;
1306
- }
1307
- _window.addEventListener('click', function (event) {
1308
- var message, selector, text;
1309
- try {
1310
- message = stringNameOfElement(event.target);
1311
- selector = stringSelectorOfElement(event.target);
1312
- text = stringTextOfElement(event.target);
1313
- }
1314
- catch (e) {
1315
- message = 'UI Click';
1316
- selector = '[unknown]';
1317
- text = '[unknown]';
1318
- }
1319
- // There's nothing to display
1320
- if (message.length === 0) {
1321
- return;
1322
- }
1323
- client.addBreadcrumb(message, {
1324
- category: 'ui.click',
1325
- metadata: {
1326
- selector: selector,
1327
- text: text,
1328
- event: event
1329
- }
1330
- });
1331
- }, true);
1332
- })();
1333
- // Breadcrumbs: instrument XMLHttpRequest
1334
- (function () {
1335
- if (!breadcrumbsEnabled('network')) {
1336
- return;
1337
- }
1338
- // -- On xhr.open: capture initial metadata
1339
- instrument(XMLHttpRequest.prototype, 'open', function (original) {
1340
- return function () {
1341
- // eslint-disable-next-line @typescript-eslint/no-this-alias
1342
- var xhr = this;
1343
- var url = arguments[1];
1344
- var method = typeof arguments[0] === 'string' ? arguments[0].toUpperCase() : arguments[0];
1345
- var message = "".concat(method, " ").concat(localURLPathname(url));
1346
- this.__hb_xhr = {
1347
- type: 'xhr',
1348
- method: method,
1349
- url: url,
1350
- message: message
1351
- };
1352
- if (typeof original === 'function') {
1353
- original.apply(xhr, arguments);
1354
- }
1355
- };
1356
- });
1357
- // -- On xhr.send: set up xhr.onreadystatechange to report breadcrumb
1358
- instrument(XMLHttpRequest.prototype, 'send', function (original) {
1359
- return function () {
1360
- // eslint-disable-next-line @typescript-eslint/no-this-alias
1361
- var xhr = this;
1362
- function onreadystatechangeHandler() {
1363
- if (xhr.readyState === 4) {
1364
- var message = void 0;
1365
- if (xhr.__hb_xhr) {
1366
- xhr.__hb_xhr.status_code = xhr.status;
1367
- message = xhr.__hb_xhr.message;
1368
- delete xhr.__hb_xhr.message;
1369
- }
1370
- client.addBreadcrumb(message || 'XMLHttpRequest', {
1371
- category: 'request',
1372
- metadata: xhr.__hb_xhr
1373
- });
1374
- }
1375
- }
1376
- if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') {
1377
- instrument(xhr, 'onreadystatechange', function (original) {
1378
- return function () {
1379
- onreadystatechangeHandler();
1380
- if (typeof original === 'function') {
1381
- // eslint-disable-next-line prefer-rest-params
1382
- original.apply(this, arguments);
1383
- }
1384
- };
1385
- });
1386
- }
1387
- else {
1388
- xhr.onreadystatechange = onreadystatechangeHandler;
1389
- }
1390
- if (typeof original === 'function') {
1391
- // eslint-disable-next-line prefer-rest-params
1392
- original.apply(xhr, arguments);
1393
- }
1394
- };
1395
- });
1396
- })();
1397
- // Breadcrumbs: instrument fetch
1398
- (function () {
1399
- if (!breadcrumbsEnabled('network')) {
1400
- return;
1401
- }
1402
- if (!nativeFetch()) {
1403
- // Polyfills use XHR.
1404
- return;
1405
- }
1406
- instrument(_window, 'fetch', function (original) {
1407
- return function () {
1408
- // eslint-disable-next-line prefer-rest-params
1409
- var input = arguments[0];
1410
- var method = 'GET';
1411
- var url;
1412
- if (typeof input === 'string') {
1413
- url = input;
1414
- }
1415
- else if ('Request' in _window && input instanceof Request) {
1416
- url = input.url;
1417
- if (input.method) {
1418
- method = input.method;
1419
- }
1420
- }
1421
- else {
1422
- url = String(input);
1423
- }
1424
- if (arguments[1] && arguments[1].method) {
1425
- method = arguments[1].method;
1426
- }
1427
- if (typeof method === 'string') {
1428
- method = method.toUpperCase();
1429
- }
1430
- var message = "".concat(method, " ").concat(localURLPathname(url));
1431
- var metadata = {
1432
- type: 'fetch',
1433
- method: method,
1434
- url: url
1435
- };
1436
- return original
1437
- .apply(this, arguments)
1438
- .then(function (response) {
1439
- metadata['status_code'] = response.status;
1440
- client.addBreadcrumb(message, {
1441
- category: 'request',
1442
- metadata: metadata
1443
- });
1444
- return response;
1445
- })
1446
- .catch(function (error) {
1447
- client.addBreadcrumb('fetch error', {
1448
- category: 'error',
1449
- metadata: metadata
1450
- });
1451
- throw error;
1452
- });
1453
- };
1454
- });
1455
- })();
1456
- // Breadcrumbs: instrument navigation
1457
- (function () {
1458
- if (!breadcrumbsEnabled('navigation')) {
1459
- return;
1460
- }
1461
- // The last known href of the current page
1462
- var lastHref = _window.location.href;
1463
- function recordUrlChange(from, to) {
1464
- lastHref = to;
1465
- client.addBreadcrumb('Page changed', {
1466
- category: 'navigation',
1467
- metadata: {
1468
- from: from,
1469
- to: to
1470
- }
1471
- });
1472
- }
1473
- // https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate
1474
- instrument(_window, 'onpopstate', function (original) {
1475
- return function () {
1476
- recordUrlChange(lastHref, _window.location.href);
1477
- if (original) {
1478
- return original.apply(this, arguments);
1479
- }
1480
- };
1481
- });
1482
- // https://developer.mozilla.org/en-US/docs/Web/API/History/pushState
1483
- // https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState
1484
- function historyWrapper(original) {
1485
- return function () {
1486
- var url = arguments.length > 2 ? arguments[2] : undefined;
1487
- if (url) {
1488
- recordUrlChange(lastHref, String(url));
1489
- }
1490
- return original.apply(this, arguments);
1491
- };
1492
- }
1493
- instrument(_window.history, 'pushState', historyWrapper);
1494
- instrument(_window.history, 'replaceState', historyWrapper);
1495
- })();
1496
- }
1497
- };
1498
- }
178
+ var require$$0 = /*@__PURE__*/getAugmentedNamespace(stackTraceParser_esm);
1499
179
 
1500
- /* eslint-disable prefer-rest-params */
1501
- function timers (_window) {
1502
- if (_window === void 0) { _window = window; }
1503
- return {
1504
- load: function (client) {
1505
- // Wrap timers
1506
- (function () {
1507
- function instrumentTimer(wrapOpts) {
1508
- return function (original) {
1509
- // See https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
1510
- return function (func, delay) {
1511
- if (typeof func === 'function') {
1512
- var args_1 = Array.prototype.slice.call(arguments, 2);
1513
- func = client.__wrap(func, wrapOpts);
1514
- return original(function () {
1515
- func.apply(void 0, args_1);
1516
- }, delay);
1517
- }
1518
- else {
1519
- return original(func, delay);
1520
- }
1521
- };
1522
- };
1523
- }
1524
- instrument(_window, 'setTimeout', instrumentTimer({ component: 'setTimeout' }));
1525
- instrument(_window, 'setInterval', instrumentTimer({ component: 'setInterval' }));
1526
- })();
1527
- }
1528
- };
1529
- }
180
+ var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
181
+ if (k2 === undefined) k2 = k;
182
+ var desc = Object.getOwnPropertyDescriptor(m, k);
183
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
184
+ desc = { enumerable: true, get: function() { return m[k]; } };
185
+ }
186
+ Object.defineProperty(o, k2, desc);
187
+ }) : (function(o, m, k, k2) {
188
+ if (k2 === undefined) k2 = k;
189
+ o[k2] = m[k];
190
+ }));
191
+ var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
192
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
193
+ }) : function(o, v) {
194
+ o["default"] = v;
195
+ });
196
+ var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
197
+ if (mod && mod.__esModule) return mod;
198
+ var result = {};
199
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
200
+ __setModuleDefault(result, mod);
201
+ return result;
202
+ };
203
+ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
204
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
205
+ return new (P || (P = Promise))(function (resolve, reject) {
206
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
207
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
208
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
209
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
210
+ });
211
+ };
212
+ Object.defineProperty(util$1, "__esModule", { value: true });
213
+ util$1.isBrowserConfig = util$1.clone = util$1.formatCGIData = util$1.filterUrl = util$1.filter = util$1.generateStackTrace = util$1.endpoint = util$1.instrument = util$1.isErrorObject = util$1.makeNotice = util$1.logger = util$1.sanitize = util$1.shallowClone = util$1.runAfterNotifyHandlers = util$1.runBeforeNotifyHandlers = util$1.getSourceForBacktrace = util$1.getCauses = util$1.makeBacktrace = util$1.objectIsExtensible = util$1.objectIsEmpty = util$1.mergeNotice = util$1.merge = void 0;
214
+ const stackTraceParser = __importStar(require$$0);
215
+ function merge$1(obj1, obj2) {
216
+ const result = {};
217
+ for (const k in obj1) {
218
+ result[k] = obj1[k];
219
+ }
220
+ for (const k in obj2) {
221
+ result[k] = obj2[k];
222
+ }
223
+ return result;
224
+ }
225
+ util$1.merge = merge$1;
226
+ function mergeNotice(notice1, notice2) {
227
+ const result = merge$1(notice1, notice2);
228
+ if (notice1.context && notice2.context) {
229
+ result.context = merge$1(notice1.context, notice2.context);
230
+ }
231
+ return result;
232
+ }
233
+ util$1.mergeNotice = mergeNotice;
234
+ function objectIsEmpty(obj) {
235
+ for (const k in obj) {
236
+ if (Object.prototype.hasOwnProperty.call(obj, k)) {
237
+ return false;
238
+ }
239
+ }
240
+ return true;
241
+ }
242
+ util$1.objectIsEmpty = objectIsEmpty;
243
+ function objectIsExtensible$1(obj) {
244
+ if (typeof Object.isExtensible !== 'function') {
245
+ return true;
246
+ }
247
+ return Object.isExtensible(obj);
248
+ }
249
+ util$1.objectIsExtensible = objectIsExtensible$1;
250
+ function makeBacktrace(stack, shift = 0) {
251
+ try {
252
+ const backtrace = stackTraceParser
253
+ .parse(stack)
254
+ .map(line => {
255
+ return {
256
+ file: line.file,
257
+ method: line.methodName,
258
+ number: line.lineNumber,
259
+ column: line.column
260
+ };
261
+ });
262
+ backtrace.splice(0, shift);
263
+ return backtrace;
264
+ }
265
+ catch (_err) {
266
+ // TODO: log error
267
+ return [];
268
+ }
269
+ }
270
+ util$1.makeBacktrace = makeBacktrace;
271
+ function getCauses(notice) {
272
+ if (notice.cause) {
273
+ const causes = [];
274
+ let cause = notice;
275
+ while (causes.length < 3 && (cause = cause.cause)) {
276
+ causes.push({
277
+ class: cause.name,
278
+ message: cause.message,
279
+ backtrace: typeof cause.stack == 'string' ? makeBacktrace(cause.stack) : null
280
+ });
281
+ }
282
+ return causes;
283
+ }
284
+ return [];
285
+ }
286
+ util$1.getCauses = getCauses;
287
+ function getSourceForBacktrace(backtrace, getSourceFileHandler) {
288
+ return __awaiter(this, void 0, void 0, function* () {
289
+ const result = [];
290
+ if (!getSourceFileHandler || !backtrace || !backtrace.length) {
291
+ return result;
292
+ }
293
+ let index = 0;
294
+ while (backtrace.length) {
295
+ const trace = backtrace.splice(0)[index];
296
+ const fileContent = yield getSourceFileHandler(trace.file);
297
+ result[index] = getSourceCodeSnippet(fileContent, trace.number);
298
+ index++;
299
+ }
300
+ return result;
301
+ });
302
+ }
303
+ util$1.getSourceForBacktrace = getSourceForBacktrace;
304
+ function runBeforeNotifyHandlers(notice, handlers) {
305
+ let result = true;
306
+ for (let i = 0, len = handlers.length; i < len; i++) {
307
+ const handler = handlers[i];
308
+ if (handler(notice) === false) {
309
+ result = false;
310
+ }
311
+ }
312
+ return result;
313
+ }
314
+ util$1.runBeforeNotifyHandlers = runBeforeNotifyHandlers;
315
+ function runAfterNotifyHandlers(notice, handlers, error) {
316
+ if (notice && notice.afterNotify) {
317
+ notice.afterNotify(error, notice);
318
+ }
319
+ for (let i = 0, len = handlers.length; i < len; i++) {
320
+ handlers[i](error, notice);
321
+ }
322
+ return true;
323
+ }
324
+ util$1.runAfterNotifyHandlers = runAfterNotifyHandlers;
325
+ // Returns a new object with properties from other object.
326
+ function shallowClone(obj) {
327
+ if (typeof (obj) !== 'object' || obj === null) {
328
+ return {};
329
+ }
330
+ const result = {};
331
+ for (const k in obj) {
332
+ result[k] = obj[k];
333
+ }
334
+ return result;
335
+ }
336
+ util$1.shallowClone = shallowClone;
337
+ function sanitize$2(obj, maxDepth = 8) {
338
+ const seenObjects = [];
339
+ function seen(obj) {
340
+ if (!obj || typeof (obj) !== 'object') {
341
+ return false;
342
+ }
343
+ for (let i = 0; i < seenObjects.length; i++) {
344
+ const value = seenObjects[i];
345
+ if (value === obj) {
346
+ return true;
347
+ }
348
+ }
349
+ seenObjects.push(obj);
350
+ return false;
351
+ }
352
+ function canSerialize(obj) {
353
+ const typeOfObj = typeof obj;
354
+ // Functions are TMI
355
+ if (/function/.test(typeOfObj)) {
356
+ // Let special toJSON method pass as it's used by JSON.stringify (#722)
357
+ return obj.name === 'toJSON';
358
+ }
359
+ // Symbols can't convert to strings.
360
+ if (/symbol/.test(typeOfObj)) {
361
+ return false;
362
+ }
363
+ if (obj === null) {
364
+ return false;
365
+ }
366
+ // No prototype, likely created with `Object.create(null)`.
367
+ if (typeof obj === 'object' && typeof obj.hasOwnProperty === 'undefined') {
368
+ return false;
369
+ }
370
+ return true;
371
+ }
372
+ function serialize(obj, depth = 0) {
373
+ if (depth >= maxDepth) {
374
+ return '[DEPTH]';
375
+ }
376
+ // Inspect invalid types
377
+ if (!canSerialize(obj)) {
378
+ return Object.prototype.toString.call(obj);
379
+ }
380
+ // Halt circular references
381
+ if (seen(obj)) {
382
+ return '[RECURSION]';
383
+ }
384
+ // Serialize inside arrays
385
+ if (Array.isArray(obj)) {
386
+ return obj.map(o => safeSerialize(o, depth + 1));
387
+ }
388
+ // Serialize inside objects
389
+ if (typeof (obj) === 'object') {
390
+ const ret = {};
391
+ for (const k in obj) {
392
+ const v = obj[k];
393
+ if (Object.prototype.hasOwnProperty.call(obj, k) && (k != null) && (v != null)) {
394
+ ret[k] = safeSerialize(v, depth + 1);
395
+ }
396
+ }
397
+ return ret;
398
+ }
399
+ // Return everything else untouched
400
+ return obj;
401
+ }
402
+ function safeSerialize(obj, depth = 0) {
403
+ try {
404
+ return serialize(obj, depth);
405
+ }
406
+ catch (e) {
407
+ return `[ERROR] ${e}`;
408
+ }
409
+ }
410
+ return safeSerialize(obj);
411
+ }
412
+ util$1.sanitize = sanitize$2;
413
+ function logger(client) {
414
+ const log = (method) => {
415
+ return function (...args) {
416
+ if (method === 'debug') {
417
+ if (!client.config.debug) {
418
+ return;
419
+ }
420
+ // Log at default level so that you don't need to also enable verbose
421
+ // logging in Chrome.
422
+ method = 'log';
423
+ }
424
+ args.unshift('[Honeybadger]');
425
+ client.config.logger[method](...args);
426
+ };
427
+ };
428
+ return {
429
+ log: log('log'),
430
+ info: log('info'),
431
+ debug: log('debug'),
432
+ warn: log('warn'),
433
+ error: log('error')
434
+ };
435
+ }
436
+ util$1.logger = logger;
437
+ /**
438
+ * Converts any object into a notice object (which at minimum has the same
439
+ * properties as Error, but supports additional Honeybadger properties.)
440
+ */
441
+ function makeNotice$1(thing) {
442
+ let notice;
443
+ if (!thing) {
444
+ notice = {};
445
+ }
446
+ else if (isErrorObject(thing)) {
447
+ const e = thing;
448
+ notice = merge$1(thing, { name: e.name, message: e.message, stack: e.stack, cause: e.cause });
449
+ }
450
+ else if (typeof thing === 'object') {
451
+ notice = shallowClone(thing);
452
+ }
453
+ else {
454
+ const m = String(thing);
455
+ notice = { message: m };
456
+ }
457
+ return notice;
458
+ }
459
+ util$1.makeNotice = makeNotice$1;
460
+ function isErrorObject(thing) {
461
+ return thing instanceof Error
462
+ || Object.prototype.toString.call(thing) === '[object Error]'; // Important for cross-realm objects
463
+ }
464
+ util$1.isErrorObject = isErrorObject;
465
+ /**
466
+ * Instrument an existing function inside an object (usually global).
467
+ * @param {!Object} object
468
+ * @param {!String} name
469
+ * @param {!Function} replacement
470
+ */
471
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
472
+ function instrument$5(object, name, replacement) {
473
+ if (!object || !name || !replacement || !(name in object)) {
474
+ return;
475
+ }
476
+ let original = object[name];
477
+ while (original && original.__hb_original) {
478
+ original = original.__hb_original;
479
+ }
480
+ try {
481
+ object[name] = replacement(original);
482
+ object[name].__hb_original = original;
483
+ }
484
+ catch (_e) {
485
+ // Ignores errors like this one:
486
+ // Error: TypeError: Cannot set property onunhandledrejection of [object Object] which has only a getter
487
+ // User-Agent: Mozilla/5.0 (Linux; Android 10; SAMSUNG SM-G960F) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/12.1 Chrome/79.0.3945.136 Mobile Safari/537.36
488
+ }
489
+ }
490
+ util$1.instrument = instrument$5;
491
+ function endpoint(base, path) {
492
+ const endpoint = base.trim().replace(/\/$/, '');
493
+ path = path.trim().replace(/(^\/|\/$)/g, '');
494
+ return `${endpoint}/${path}`;
495
+ }
496
+ util$1.endpoint = endpoint;
497
+ function generateStackTrace() {
498
+ try {
499
+ throw new Error('');
500
+ }
501
+ catch (e) {
502
+ if (e.stack) {
503
+ return e.stack;
504
+ }
505
+ }
506
+ const maxStackSize = 10;
507
+ const stack = [];
508
+ let curr = arguments.callee;
509
+ while (curr && stack.length < maxStackSize) {
510
+ if (/function(?:\s+([\w$]+))+\s*\(/.test(curr.toString())) {
511
+ stack.push(RegExp.$1 || '<anonymous>');
512
+ }
513
+ else {
514
+ stack.push('<anonymous>');
515
+ }
516
+ try {
517
+ curr = curr.caller;
518
+ }
519
+ catch (e) {
520
+ break;
521
+ }
522
+ }
523
+ return stack.join('\n');
524
+ }
525
+ util$1.generateStackTrace = generateStackTrace;
526
+ function filter$1(obj, filters) {
527
+ if (!is('Object', obj)) {
528
+ return;
529
+ }
530
+ if (!is('Array', filters)) {
531
+ filters = [];
532
+ }
533
+ const seen = [];
534
+ function filter(obj) {
535
+ let k, newObj;
536
+ if (is('Object', obj) || is('Array', obj)) {
537
+ if (seen.indexOf(obj) !== -1) {
538
+ return '[CIRCULAR DATA STRUCTURE]';
539
+ }
540
+ seen.push(obj);
541
+ }
542
+ if (is('Object', obj)) {
543
+ newObj = {};
544
+ for (k in obj) {
545
+ if (filterMatch(k, filters)) {
546
+ newObj[k] = '[FILTERED]';
547
+ }
548
+ else {
549
+ newObj[k] = filter(obj[k]);
550
+ }
551
+ }
552
+ return newObj;
553
+ }
554
+ if (is('Array', obj)) {
555
+ return obj.map(function (v) {
556
+ return filter(v);
557
+ });
558
+ }
559
+ if (is('Function', obj)) {
560
+ return '[FUNC]';
561
+ }
562
+ return obj;
563
+ }
564
+ return filter(obj);
565
+ }
566
+ util$1.filter = filter$1;
567
+ function filterMatch(key, filters) {
568
+ for (let i = 0; i < filters.length; i++) {
569
+ if (key.toLowerCase().indexOf(filters[i].toLowerCase()) !== -1) {
570
+ return true;
571
+ }
572
+ }
573
+ return false;
574
+ }
575
+ function is(type, obj) {
576
+ const klass = Object.prototype.toString.call(obj).slice(8, -1);
577
+ return obj !== undefined && obj !== null && klass === type;
578
+ }
579
+ function filterUrl(url, filters) {
580
+ if (!filters) {
581
+ return url;
582
+ }
583
+ if (typeof url !== 'string') {
584
+ return url;
585
+ }
586
+ const query = url.split(/\?/, 2)[1];
587
+ if (!query) {
588
+ return url;
589
+ }
590
+ let result = url;
591
+ query.split(/[&]\s?/).forEach((pair) => {
592
+ const [key, value] = pair.split('=', 2);
593
+ if (filterMatch(key, filters)) {
594
+ result = result.replace(`${key}=${value}`, `${key}=[FILTERED]`);
595
+ }
596
+ });
597
+ return result;
598
+ }
599
+ util$1.filterUrl = filterUrl;
600
+ function formatCGIData(vars, prefix = '') {
601
+ const formattedVars = {};
602
+ Object.keys(vars).forEach(function (key) {
603
+ const formattedKey = prefix + key.replace(/\W/g, '_').toUpperCase();
604
+ formattedVars[formattedKey] = vars[key];
605
+ });
606
+ return formattedVars;
607
+ }
608
+ util$1.formatCGIData = formatCGIData;
609
+ function clone(obj) {
610
+ return JSON.parse(JSON.stringify(obj));
611
+ }
612
+ util$1.clone = clone;
613
+ function getSourceCodeSnippet(fileData, lineNumber, sourceRadius = 2) {
614
+ if (!fileData) {
615
+ return null;
616
+ }
617
+ const lines = fileData.split('\n');
618
+ // add one empty line because array index starts from 0, but error line number is counted from 1
619
+ lines.unshift('');
620
+ const start = lineNumber - sourceRadius;
621
+ const end = lineNumber + sourceRadius;
622
+ const result = {};
623
+ for (let i = start; i <= end; i++) {
624
+ const line = lines[i];
625
+ if (typeof line === 'string') {
626
+ result[i] = line;
627
+ }
628
+ }
629
+ return result;
630
+ }
631
+ function isBrowserConfig(config) {
632
+ return config.async !== undefined;
633
+ }
634
+ util$1.isBrowserConfig = isBrowserConfig;
1530
635
 
1531
- function eventListeners (_window) {
1532
- if (_window === void 0) { _window = window; }
1533
- return {
1534
- load: function (client) {
1535
- // Wrap event listeners
1536
- // Event targets borrowed from bugsnag-js:
1537
- // See https://github.com/bugsnag/bugsnag-js/blob/d55af916a4d3c7757f979d887f9533fe1a04cc93/src/bugsnag.js#L542
1538
- var targets = ['EventTarget', 'Window', 'Node', 'ApplicationCache', 'AudioTrackList', 'ChannelMergerNode', 'CryptoOperation', 'EventSource', 'FileReader', 'HTMLUnknownElement', 'IDBDatabase', 'IDBRequest', 'IDBTransaction', 'KeyOperation', 'MediaController', 'MessagePort', 'ModalWindow', 'Notification', 'SVGElementInstance', 'Screen', 'TextTrack', 'TextTrackCue', 'TextTrackList', 'WebSocket', 'WebSocketWorker', 'Worker', 'XMLHttpRequest', 'XMLHttpRequestEventTarget', 'XMLHttpRequestUpload'];
1539
- targets.forEach(function (prop) {
1540
- var prototype = _window[prop] && _window[prop].prototype;
1541
- if (prototype && Object.prototype.hasOwnProperty.call(prototype, 'addEventListener')) {
1542
- instrument(prototype, 'addEventListener', function (original) {
1543
- var wrapOpts = { component: "".concat(prop, ".prototype.addEventListener") };
1544
- // See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
1545
- return function (type, listener, useCapture, wantsUntrusted) {
1546
- try {
1547
- if (listener && listener.handleEvent != null) {
1548
- listener.handleEvent = client.__wrap(listener.handleEvent, wrapOpts);
1549
- }
1550
- }
1551
- catch (e) {
1552
- // Ignore 'Permission denied to access property "handleEvent"' errors.
1553
- client.logger.error(e);
1554
- }
1555
- return original.call(this, type, client.__wrap(listener, wrapOpts), useCapture, wantsUntrusted);
1556
- };
1557
- });
1558
- instrument(prototype, 'removeEventListener', function (original) {
1559
- return function (type, listener, useCapture, wantsUntrusted) {
1560
- original.call(this, type, listener, useCapture, wantsUntrusted);
1561
- return original.call(this, type, client.__wrap(listener), useCapture, wantsUntrusted);
1562
- };
1563
- });
1564
- }
1565
- });
1566
- }
1567
- };
1568
- }
636
+ var store = {};
1569
637
 
1570
- var BrowserTransport = /** @class */ (function () {
1571
- function BrowserTransport() {
1572
- }
1573
- BrowserTransport.prototype.send = function (options, payload) {
1574
- return new Promise(function (resolve, reject) {
1575
- try {
1576
- var x_1 = new XMLHttpRequest();
1577
- x_1.open(options.method, options.endpoint, options.async);
1578
- if (Object.keys(options.headers || []).length) {
1579
- for (var i in options.headers) {
1580
- if (typeof options.headers[i] !== 'undefined') {
1581
- x_1.setRequestHeader(i, String(options.headers[i]));
1582
- }
1583
- }
1584
- }
1585
- x_1.send(payload ? JSON.stringify(sanitize(payload, options.maxObjectDepth)) : undefined);
1586
- x_1.onload = function () { return resolve({ statusCode: x_1.status, body: x_1.response }); };
1587
- }
1588
- catch (err) {
1589
- reject(err);
1590
- }
1591
- });
1592
- };
1593
- return BrowserTransport;
1594
- }());
638
+ Object.defineProperty(store, "__esModule", { value: true });
639
+ store.GlobalStore = void 0;
640
+ class GlobalStore {
641
+ constructor(store) {
642
+ this.store = store;
643
+ }
644
+ getStore() {
645
+ return this.store;
646
+ }
647
+ run(store, callback, ...args) {
648
+ this.store = store;
649
+ return callback(...args);
650
+ }
651
+ }
652
+ store.GlobalStore = GlobalStore;
1595
653
 
1596
- var Honeybadger = /** @class */ (function (_super) {
1597
- __extends(Honeybadger, _super);
1598
- function Honeybadger(opts) {
1599
- if (opts === void 0) { opts = {}; }
1600
- var _this = _super.call(this, __assign({ async: true, maxErrors: null, projectRoot: window.location.protocol + '//' + window.location.host }, opts), new BrowserTransport()) || this;
1601
- /** @internal */
1602
- _this.__errorsSent = 0;
1603
- /** @internal */
1604
- _this.__lastWrapErr = undefined;
1605
- /** @internal */
1606
- _this.__beforeNotifyHandlers = [
1607
- function (notice) {
1608
- if (_this.__exceedsMaxErrors()) {
1609
- _this.logger.debug('Dropping notice: max errors exceeded', notice);
1610
- return false;
1611
- }
1612
- if (!notice.url) {
1613
- notice.url = document.URL;
1614
- }
1615
- _this.__incrementErrorsCount();
1616
- return true;
1617
- }
1618
- ];
1619
- return _this;
1620
- }
1621
- Honeybadger.prototype.configure = function (opts) {
1622
- if (opts === void 0) { opts = {}; }
1623
- return _super.prototype.configure.call(this, opts);
1624
- };
1625
- Honeybadger.prototype.resetMaxErrors = function () {
1626
- return (this.__errorsSent = 0);
1627
- };
1628
- Honeybadger.prototype.factory = function (opts) {
1629
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1630
- return new Honeybadger(opts);
1631
- };
1632
- Honeybadger.prototype.checkIn = function (_id) {
1633
- throw new Error('Honeybadger.checkIn() is not supported on the browser');
1634
- };
1635
- /** @internal */
1636
- Honeybadger.prototype.__buildPayload = function (notice) {
1637
- var cgiData = {
1638
- HTTP_USER_AGENT: undefined,
1639
- HTTP_REFERER: undefined,
1640
- HTTP_COOKIE: undefined
1641
- };
1642
- cgiData.HTTP_USER_AGENT = navigator.userAgent;
1643
- if (document.referrer.match(/\S/)) {
1644
- cgiData.HTTP_REFERER = document.referrer;
1645
- }
1646
- var cookiesObject;
1647
- if (typeof notice.cookies === 'string') {
1648
- cookiesObject = decodeCookie(notice.cookies);
1649
- }
1650
- else {
1651
- cookiesObject = notice.cookies;
1652
- }
1653
- if (cookiesObject) {
1654
- cgiData.HTTP_COOKIE = encodeCookie(filter(cookiesObject, this.config.filters));
1655
- }
1656
- var payload = _super.prototype.__buildPayload.call(this, notice);
1657
- payload.request.cgi_data = merge(cgiData, payload.request.cgi_data);
1658
- return payload;
1659
- };
1660
- /**
1661
- * wrap always returns the same function so that callbacks can be removed via
1662
- * removeEventListener.
1663
- * @internal
1664
- */
1665
- Honeybadger.prototype.__wrap = function (f, opts) {
1666
- if (opts === void 0) { opts = {}; }
1667
- var func = f;
1668
- if (!opts) {
1669
- opts = {};
1670
- }
1671
- try {
1672
- if (typeof func !== 'function') {
1673
- return func;
1674
- }
1675
- if (!objectIsExtensible(func)) {
1676
- return func;
1677
- }
1678
- if (!func.___hb) {
1679
- // eslint-disable-next-line @typescript-eslint/no-this-alias
1680
- var client_1 = this;
1681
- func.___hb = function () {
1682
- if (preferCatch) {
1683
- try {
1684
- // eslint-disable-next-line prefer-rest-params
1685
- return func.apply(this, arguments);
1686
- }
1687
- catch (err) {
1688
- if (client_1.__lastWrapErr === err) {
1689
- throw (err);
1690
- }
1691
- client_1.__lastWrapErr = err;
1692
- ignoreNextOnError();
1693
- client_1.addBreadcrumb(opts.component ? "".concat(opts.component, ": ").concat(err.name) : err.name, {
1694
- category: 'error',
1695
- metadata: {
1696
- message: err.message,
1697
- name: err.name,
1698
- stack: err.stack
1699
- }
1700
- });
1701
- if (client_1.config.enableUncaught) {
1702
- client_1.notify(err);
1703
- }
1704
- throw (err);
1705
- }
1706
- }
1707
- else {
1708
- // eslint-disable-next-line prefer-rest-params
1709
- return func.apply(this, arguments);
1710
- }
1711
- };
1712
- }
1713
- func.___hb.___hb = func.___hb;
1714
- return func.___hb;
1715
- }
1716
- catch (_e) {
1717
- return func;
1718
- }
1719
- };
1720
- /** @internal */
1721
- Honeybadger.prototype.__incrementErrorsCount = function () {
1722
- return this.__errorsSent++;
1723
- };
1724
- /** @internal */
1725
- Honeybadger.prototype.__exceedsMaxErrors = function () {
1726
- return this.config.maxErrors && this.__errorsSent >= this.config.maxErrors;
1727
- };
1728
- return Honeybadger;
1729
- }(Client));
1730
- var browser = new Honeybadger({
1731
- __plugins: [
1732
- onError(),
1733
- onUnhandledRejection(),
1734
- timers(),
1735
- eventListeners(),
1736
- breadcrumbs()
1737
- ]
1738
- });
654
+ Object.defineProperty(client, "__esModule", { value: true });
655
+ client.Client = void 0;
656
+ const util_1$2 = util$1;
657
+ const store_1 = store;
658
+ const notifier = {
659
+ name: 'honeybadger-js',
660
+ url: 'https://github.com/honeybadger-io/honeybadger-js',
661
+ version: '4.1.0'
662
+ };
663
+ // Split at commas and spaces
664
+ const TAG_SEPARATOR = /,|\s+/;
665
+ // Checks for non-blank characters
666
+ const NOT_BLANK = /\S/;
667
+ class Client {
668
+ constructor(opts = {}, transport) {
669
+ this.__pluginsExecuted = false;
670
+ this.__store = null;
671
+ this.__beforeNotifyHandlers = [];
672
+ this.__afterNotifyHandlers = [];
673
+ this.config = Object.assign({ apiKey: null, endpoint: 'https://api.honeybadger.io', environment: null, hostname: null, projectRoot: null, component: null, action: null, revision: null, reportData: null, breadcrumbsEnabled: true, maxBreadcrumbs: 40, maxObjectDepth: 8, logger: console, developmentEnvironments: ['dev', 'development', 'test'], debug: false, tags: null, enableUncaught: true, enableUnhandledRejection: true, afterUncaught: () => true, filters: ['creditcard', 'password'], __plugins: [] }, opts);
674
+ // First, we go with the global (shared) store.
675
+ // Webserver middleware can then switch to the AsyncStore for async context tracking.
676
+ this.__store = new store_1.GlobalStore({ context: {}, breadcrumbs: [] });
677
+ this.__transport = transport;
678
+ this.logger = (0, util_1$2.logger)(this);
679
+ }
680
+ getVersion() {
681
+ return notifier.version;
682
+ }
683
+ configure(opts = {}) {
684
+ for (const k in opts) {
685
+ this.config[k] = opts[k];
686
+ }
687
+ if (!this.__pluginsExecuted) {
688
+ this.__pluginsExecuted = true;
689
+ this.config.__plugins.forEach((plugin) => plugin.load(this));
690
+ }
691
+ return this;
692
+ }
693
+ __setStore(store) {
694
+ this.__store = store;
695
+ }
696
+ beforeNotify(handler) {
697
+ this.__beforeNotifyHandlers.push(handler);
698
+ return this;
699
+ }
700
+ afterNotify(handler) {
701
+ this.__afterNotifyHandlers.push(handler);
702
+ return this;
703
+ }
704
+ setContext(context) {
705
+ if (typeof context === 'object') {
706
+ const store = this.__store.getStore();
707
+ store.context = (0, util_1$2.merge)(store.context, context);
708
+ }
709
+ return this;
710
+ }
711
+ resetContext(context) {
712
+ this.logger.warn('Deprecation warning: `Honeybadger.resetContext()` has been deprecated; please use `Honeybadger.clear()` instead.');
713
+ const store = this.__store.getStore();
714
+ if (typeof context === 'object' && context !== null) {
715
+ store.context = context;
716
+ }
717
+ else {
718
+ store.context = {};
719
+ }
720
+ return this;
721
+ }
722
+ clear() {
723
+ const store = this.__store.getStore();
724
+ store.context = {};
725
+ store.breadcrumbs = [];
726
+ return this;
727
+ }
728
+ notify(noticeable, name = undefined, extra = undefined) {
729
+ let preConditionError = null;
730
+ const notice = this.makeNotice(noticeable, name, extra);
731
+ if (!notice) {
732
+ this.logger.debug('failed to build error report');
733
+ preConditionError = new Error('failed to build error report');
734
+ }
735
+ if (!preConditionError && this.config.reportData === false) {
736
+ this.logger.debug('skipping error report: honeybadger.js is disabled', notice);
737
+ preConditionError = new Error('honeybadger.js is disabled');
738
+ }
739
+ if (!preConditionError && this.__developmentMode()) {
740
+ this.logger.log('honeybadger.js is in development mode; the following error report will be sent in production.', notice);
741
+ preConditionError = new Error('honeybadger.js is in development mode');
742
+ }
743
+ if (!preConditionError && !this.config.apiKey) {
744
+ this.logger.warn('could not send error report: no API key has been configured', notice);
745
+ preConditionError = new Error('missing API key');
746
+ }
747
+ // we need to have the source file data before the beforeNotifyHandlers,
748
+ // in case they modify them
749
+ const sourceCodeData = notice && notice.backtrace ? notice.backtrace.map(trace => (0, util_1$2.shallowClone)(trace)) : null;
750
+ const beforeNotifyResult = (0, util_1$2.runBeforeNotifyHandlers)(notice, this.__beforeNotifyHandlers);
751
+ if (!preConditionError && !beforeNotifyResult) {
752
+ this.logger.debug('skipping error report: beforeNotify handlers returned false', notice);
753
+ preConditionError = new Error('beforeNotify handlers returned false');
754
+ }
755
+ if (preConditionError) {
756
+ (0, util_1$2.runAfterNotifyHandlers)(notice, this.__afterNotifyHandlers, preConditionError);
757
+ return false;
758
+ }
759
+ this.addBreadcrumb('Honeybadger Notice', {
760
+ category: 'notice',
761
+ metadata: {
762
+ message: notice.message,
763
+ name: notice.name,
764
+ stack: notice.stack
765
+ }
766
+ });
767
+ const breadcrumbs = this.__getStoreContentsOrDefault().breadcrumbs;
768
+ notice.__breadcrumbs = this.config.breadcrumbsEnabled ? breadcrumbs.slice() : [];
769
+ (0, util_1$2.getSourceForBacktrace)(sourceCodeData, this.__getSourceFileHandler)
770
+ .then(sourcePerTrace => {
771
+ sourcePerTrace.forEach((source, index) => {
772
+ notice.backtrace[index].source = source;
773
+ });
774
+ const payload = this.__buildPayload(notice);
775
+ this.__transport
776
+ .send({
777
+ headers: {
778
+ 'X-API-Key': this.config.apiKey,
779
+ 'Content-Type': 'application/json',
780
+ 'Accept': 'text/json, application/json'
781
+ },
782
+ method: 'POST',
783
+ endpoint: (0, util_1$2.endpoint)(this.config.endpoint, '/v1/notices/js'),
784
+ maxObjectDepth: this.config.maxObjectDepth,
785
+ logger: this.logger,
786
+ async: (0, util_1$2.isBrowserConfig)(this.config) ? this.config.async : undefined,
787
+ }, payload)
788
+ .then(res => {
789
+ if (res.statusCode !== 201) {
790
+ (0, util_1$2.runAfterNotifyHandlers)(notice, this.__afterNotifyHandlers, new Error(`Bad HTTP response: ${res.statusCode}`));
791
+ this.logger.warn(`Error report failed: unknown response from server. code=${res.statusCode}`);
792
+ return;
793
+ }
794
+ const uuid = JSON.parse(res.body).id;
795
+ (0, util_1$2.runAfterNotifyHandlers)((0, util_1$2.merge)(notice, {
796
+ id: uuid
797
+ }), this.__afterNotifyHandlers);
798
+ this.logger.info(`Error report sent ⚡ https://app.honeybadger.io/notice/${uuid}`);
799
+ })
800
+ .catch(err => {
801
+ this.logger.error('Error report failed: an unknown error occurred.', `message=${err.message}`);
802
+ (0, util_1$2.runAfterNotifyHandlers)(notice, this.__afterNotifyHandlers, err);
803
+ });
804
+ });
805
+ return true;
806
+ }
807
+ /**
808
+ * An async version of {@link notify} that resolves only after the notice has been reported to Honeybadger.
809
+ * Implemented using the {@link afterNotify} hook.
810
+ * Rejects if for any reason the report failed to be reported.
811
+ * Useful in serverless environments (AWS Lambda).
812
+ */
813
+ notifyAsync(noticeable, name = undefined, extra = undefined) {
814
+ return new Promise((resolve, reject) => {
815
+ const applyAfterNotify = (partialNotice) => {
816
+ const originalAfterNotify = partialNotice.afterNotify;
817
+ partialNotice.afterNotify = (err) => {
818
+ originalAfterNotify === null || originalAfterNotify === void 0 ? void 0 : originalAfterNotify.call(this, err);
819
+ if (err) {
820
+ return reject(err);
821
+ }
822
+ resolve();
823
+ };
824
+ };
825
+ // We have to respect any afterNotify hooks that come from the arguments
826
+ let objectToOverride;
827
+ if (noticeable.afterNotify) {
828
+ objectToOverride = noticeable;
829
+ }
830
+ else if (name && name.afterNotify) {
831
+ objectToOverride = name;
832
+ }
833
+ else if (extra && extra.afterNotify) {
834
+ objectToOverride = extra;
835
+ }
836
+ else if (name && typeof name === 'object') {
837
+ objectToOverride = name;
838
+ }
839
+ else if (extra) {
840
+ objectToOverride = extra;
841
+ }
842
+ else {
843
+ objectToOverride = name = {};
844
+ }
845
+ applyAfterNotify(objectToOverride);
846
+ this.notify(noticeable, name, extra);
847
+ });
848
+ }
849
+ makeNotice(noticeable, name = undefined, extra = undefined) {
850
+ let notice = (0, util_1$2.makeNotice)(noticeable);
851
+ if (name && !(typeof name === 'object')) {
852
+ const n = String(name);
853
+ name = { name: n };
854
+ }
855
+ if (name) {
856
+ notice = (0, util_1$2.mergeNotice)(notice, name);
857
+ }
858
+ if (typeof extra === 'object' && extra !== null) {
859
+ notice = (0, util_1$2.mergeNotice)(notice, extra);
860
+ }
861
+ if ((0, util_1$2.objectIsEmpty)(notice)) {
862
+ return null;
863
+ }
864
+ const context = this.__getStoreContentsOrDefault().context;
865
+ const noticeTags = this.__constructTags(notice.tags);
866
+ const contextTags = this.__constructTags(context['tags']);
867
+ const configTags = this.__constructTags(this.config.tags);
868
+ // Turning into a Set will remove duplicates
869
+ const tags = noticeTags.concat(contextTags).concat(configTags);
870
+ const uniqueTags = tags.filter((item, index) => tags.indexOf(item) === index);
871
+ notice = (0, util_1$2.merge)(notice, {
872
+ name: notice.name || 'Error',
873
+ context: (0, util_1$2.merge)(context, notice.context),
874
+ projectRoot: notice.projectRoot || this.config.projectRoot,
875
+ environment: notice.environment || this.config.environment,
876
+ component: notice.component || this.config.component,
877
+ action: notice.action || this.config.action,
878
+ revision: notice.revision || this.config.revision,
879
+ tags: uniqueTags,
880
+ });
881
+ let backtraceShift = 0;
882
+ if (typeof notice.stack !== 'string' || !notice.stack.trim()) {
883
+ notice.stack = (0, util_1$2.generateStackTrace)();
884
+ backtraceShift = 2;
885
+ }
886
+ notice.backtrace = (0, util_1$2.makeBacktrace)(notice.stack, backtraceShift);
887
+ return notice;
888
+ }
889
+ addBreadcrumb(message, opts) {
890
+ if (!this.config.breadcrumbsEnabled) {
891
+ return;
892
+ }
893
+ opts = opts || {};
894
+ const metadata = (0, util_1$2.shallowClone)(opts.metadata);
895
+ const category = opts.category || 'custom';
896
+ const timestamp = new Date().toISOString();
897
+ const store = this.__store.getStore();
898
+ let breadcrumbs = store.breadcrumbs;
899
+ breadcrumbs.push({
900
+ category: category,
901
+ message: message,
902
+ metadata: metadata,
903
+ timestamp: timestamp
904
+ });
905
+ const limit = this.config.maxBreadcrumbs;
906
+ if (breadcrumbs.length > limit) {
907
+ breadcrumbs = breadcrumbs.slice(breadcrumbs.length - limit);
908
+ }
909
+ store.breadcrumbs = breadcrumbs;
910
+ return this;
911
+ }
912
+ __developmentMode() {
913
+ if (this.config.reportData === true) {
914
+ return false;
915
+ }
916
+ return (this.config.environment && this.config.developmentEnvironments.includes(this.config.environment));
917
+ }
918
+ __buildPayload(notice) {
919
+ const headers = (0, util_1$2.filter)(notice.headers, this.config.filters) || {};
920
+ const cgiData = (0, util_1$2.filter)(Object.assign(Object.assign({}, notice.cgiData), (0, util_1$2.formatCGIData)(headers, 'HTTP_')), this.config.filters);
921
+ return {
922
+ notifier: notifier,
923
+ breadcrumbs: {
924
+ enabled: !!this.config.breadcrumbsEnabled,
925
+ trail: notice.__breadcrumbs || []
926
+ },
927
+ error: {
928
+ class: notice.name,
929
+ message: notice.message,
930
+ backtrace: notice.backtrace,
931
+ fingerprint: notice.fingerprint,
932
+ tags: notice.tags,
933
+ causes: (0, util_1$2.getCauses)(notice),
934
+ },
935
+ request: {
936
+ url: (0, util_1$2.filterUrl)(notice.url, this.config.filters),
937
+ component: notice.component,
938
+ action: notice.action,
939
+ context: notice.context,
940
+ cgi_data: cgiData,
941
+ params: (0, util_1$2.filter)(notice.params, this.config.filters) || {},
942
+ session: (0, util_1$2.filter)(notice.session, this.config.filters) || {}
943
+ },
944
+ server: {
945
+ project_root: notice.projectRoot,
946
+ environment_name: notice.environment,
947
+ revision: notice.revision,
948
+ hostname: this.config.hostname,
949
+ time: new Date().toUTCString()
950
+ },
951
+ details: notice.details || {}
952
+ };
953
+ }
954
+ __constructTags(tags) {
955
+ if (!tags) {
956
+ return [];
957
+ }
958
+ return tags.toString().split(TAG_SEPARATOR).filter((tag) => NOT_BLANK.test(tag));
959
+ }
960
+ /**
961
+ * For ALS, the store may be uninitialized (if .run()` has not been called).
962
+ * This provides an easy way to read the existing store object or fall back to a default.
963
+ * Returns *a copy* of the s tore contents.
964
+ */
965
+ __getStoreContentsOrDefault() {
966
+ const existingStoreContents = this.__store.getStore();
967
+ const storeContents = existingStoreContents || {};
968
+ return Object.assign({ context: {}, breadcrumbs: [] }, storeContents);
969
+ }
970
+ }
971
+ client.Client = Client;
1739
972
 
1740
- return browser;
973
+ var types = {};
974
+
975
+ Object.defineProperty(types, "__esModule", { value: true });
976
+
977
+ (function (exports) {
978
+ var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
979
+ if (k2 === undefined) k2 = k;
980
+ var desc = Object.getOwnPropertyDescriptor(m, k);
981
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
982
+ desc = { enumerable: true, get: function() { return m[k]; } };
983
+ }
984
+ Object.defineProperty(o, k2, desc);
985
+ }) : (function(o, m, k, k2) {
986
+ if (k2 === undefined) k2 = k;
987
+ o[k2] = m[k];
988
+ }));
989
+ var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
990
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
991
+ }) : function(o, v) {
992
+ o["default"] = v;
993
+ });
994
+ var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
995
+ if (mod && mod.__esModule) return mod;
996
+ var result = {};
997
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
998
+ __setModuleDefault(result, mod);
999
+ return result;
1000
+ };
1001
+ Object.defineProperty(exports, "__esModule", { value: true });
1002
+ exports.Util = exports.Types = exports.Store = exports.Client = void 0;
1003
+ var client_1 = client;
1004
+ Object.defineProperty(exports, "Client", { enumerable: true, get: function () { return client_1.Client; } });
1005
+ exports.Store = __importStar(store);
1006
+ exports.Types = __importStar(types);
1007
+ exports.Util = __importStar(util$1);
1008
+ } (src));
1009
+
1010
+ var util = {};
1011
+
1012
+ Object.defineProperty(util, "__esModule", { value: true });
1013
+ util.preferCatch = util.encodeCookie = util.decodeCookie = util.localURLPathname = util.parseURL = util.nativeFetch = util.stringTextOfElement = util.stringSelectorOfElement = util.stringNameOfElement = void 0;
1014
+ /**
1015
+ * Converts an HTMLElement into a human-readable string.
1016
+ * @param {!HTMLElement} element
1017
+ * @return {string}
1018
+ */
1019
+ function stringNameOfElement(element) {
1020
+ if (!element || !element.tagName) {
1021
+ return '';
1022
+ }
1023
+ let name = element.tagName.toLowerCase();
1024
+ // Ignore the root <html> element in selectors and events.
1025
+ if (name === 'html') {
1026
+ return '';
1027
+ }
1028
+ if (element.id) {
1029
+ name += `#${element.id}`;
1030
+ }
1031
+ const stringClassNames = element.getAttribute('class');
1032
+ if (stringClassNames) {
1033
+ stringClassNames.split(/\s+/).forEach(className => {
1034
+ name += `.${className}`;
1035
+ });
1036
+ }
1037
+ ['alt', 'name', 'title', 'type'].forEach(attrName => {
1038
+ const attr = element.getAttribute(attrName);
1039
+ if (attr) {
1040
+ name += `[${attrName}="${attr}"]`;
1041
+ }
1042
+ });
1043
+ const siblings = getSiblings(element);
1044
+ if (siblings.length > 1) {
1045
+ name += `:nth-child(${Array.prototype.indexOf.call(siblings, element) + 1})`;
1046
+ }
1047
+ return name;
1048
+ }
1049
+ util.stringNameOfElement = stringNameOfElement;
1050
+ function stringSelectorOfElement(element) {
1051
+ const name = stringNameOfElement(element);
1052
+ if (element.parentNode && element.parentNode.tagName) {
1053
+ const parentName = stringSelectorOfElement(element.parentNode);
1054
+ if (parentName.length > 0) {
1055
+ return `${parentName} > ${name}`;
1056
+ }
1057
+ }
1058
+ return name;
1059
+ }
1060
+ util.stringSelectorOfElement = stringSelectorOfElement;
1061
+ function stringTextOfElement(element) {
1062
+ let text = element.textContent || element.innerText || '';
1063
+ if (!text && (element.type === 'submit' || element.type === 'button')) {
1064
+ text = element.value;
1065
+ }
1066
+ return truncate(text.trim(), 300);
1067
+ }
1068
+ util.stringTextOfElement = stringTextOfElement;
1069
+ function nativeFetch() {
1070
+ if (!window.fetch) {
1071
+ return false;
1072
+ }
1073
+ if (isNative(window.fetch)) {
1074
+ return true;
1075
+ }
1076
+ // If fetch isn't native, it may be wrapped by someone else. Try to get
1077
+ // a pristine function from an iframe.
1078
+ try {
1079
+ const sandbox = document.createElement('iframe');
1080
+ sandbox.style.display = 'none';
1081
+ document.head.appendChild(sandbox);
1082
+ const result = sandbox.contentWindow.fetch && isNative(sandbox.contentWindow.fetch);
1083
+ document.head.removeChild(sandbox);
1084
+ return result;
1085
+ }
1086
+ catch (err) {
1087
+ if (console && console.warn) {
1088
+ console.warn('failed to detect native fetch via iframe: ' + err);
1089
+ }
1090
+ }
1091
+ return false;
1092
+ }
1093
+ util.nativeFetch = nativeFetch;
1094
+ function isNative(func) {
1095
+ return func.toString().indexOf('native') !== -1;
1096
+ }
1097
+ function parseURL(url) {
1098
+ // Regexp: https://tools.ietf.org/html/rfc3986#appendix-B
1099
+ const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/) || {};
1100
+ return {
1101
+ protocol: match[2],
1102
+ host: match[4],
1103
+ pathname: match[5]
1104
+ };
1105
+ }
1106
+ util.parseURL = parseURL;
1107
+ function localURLPathname(url) {
1108
+ const parsed = parseURL(url);
1109
+ const parsedDocURL = parseURL(document.URL);
1110
+ // URL must be relative
1111
+ if (!parsed.host || !parsed.protocol) {
1112
+ return parsed.pathname;
1113
+ }
1114
+ // Same domain
1115
+ if (parsed.protocol === parsedDocURL.protocol && parsed.host === parsedDocURL.host) {
1116
+ return parsed.pathname;
1117
+ }
1118
+ // x-domain
1119
+ return `${parsed.protocol}://${parsed.host}${parsed.pathname}`;
1120
+ }
1121
+ util.localURLPathname = localURLPathname;
1122
+ function decodeCookie(string) {
1123
+ const result = {};
1124
+ string.split(/[;,]\s?/).forEach((pair) => {
1125
+ const [key, value] = pair.split('=', 2);
1126
+ result[key] = value;
1127
+ });
1128
+ return result;
1129
+ }
1130
+ util.decodeCookie = decodeCookie;
1131
+ function encodeCookie(object) {
1132
+ if (typeof object !== 'object') {
1133
+ return undefined;
1134
+ }
1135
+ const cookies = [];
1136
+ for (const k in object) {
1137
+ cookies.push(k + '=' + object[k]);
1138
+ }
1139
+ return cookies.join(';');
1140
+ }
1141
+ util.encodeCookie = encodeCookie;
1142
+ // Helpers
1143
+ function getSiblings(element) {
1144
+ try {
1145
+ const nodes = element.parentNode.childNodes;
1146
+ const siblings = [];
1147
+ Array.prototype.forEach.call(nodes, node => {
1148
+ if (node.tagName && node.tagName === element.tagName) {
1149
+ siblings.push(node);
1150
+ }
1151
+ });
1152
+ return siblings;
1153
+ }
1154
+ catch (e) {
1155
+ return [];
1156
+ }
1157
+ }
1158
+ function truncate(string, length) {
1159
+ if (string.length > length) {
1160
+ string = string.substr(0, length) + '...';
1161
+ }
1162
+ return string;
1163
+ }
1164
+ // Used to decide which error handling method to use when wrapping async
1165
+ // handlers: try/catch, or `window.onerror`. When available, `window.onerror`
1166
+ // will provide more information in modern browsers.
1167
+ util.preferCatch = (function () {
1168
+ let preferCatch = true;
1169
+ // IE < 10
1170
+ if (!window.atob) {
1171
+ preferCatch = false;
1172
+ }
1173
+ // Modern browsers support the full ErrorEvent API
1174
+ // See https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent
1175
+ if (window.ErrorEvent) {
1176
+ try {
1177
+ if ((new window.ErrorEvent('')).colno === 0) {
1178
+ preferCatch = false;
1179
+ }
1180
+ // eslint-disable-next-line no-empty
1181
+ }
1182
+ catch (_e) { }
1183
+ }
1184
+ return preferCatch;
1185
+ })();
1186
+
1187
+ var onerror = {};
1188
+
1189
+ Object.defineProperty(onerror, "__esModule", { value: true });
1190
+ onerror.onError = onerror.ignoreNextOnError = void 0;
1191
+ /* eslint-disable prefer-rest-params */
1192
+ const core_1$6 = src;
1193
+ const { instrument: instrument$4, makeNotice } = core_1$6.Util;
1194
+ let ignoreOnError = 0;
1195
+ let currentTimeout;
1196
+ function ignoreNextOnError() {
1197
+ ignoreOnError += 1;
1198
+ clearTimeout(currentTimeout);
1199
+ currentTimeout = setTimeout(() => {
1200
+ ignoreOnError = 0;
1201
+ });
1202
+ }
1203
+ onerror.ignoreNextOnError = ignoreNextOnError;
1204
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1205
+ function onError(_window = window) {
1206
+ return {
1207
+ load: (client) => {
1208
+ instrument$4(_window, 'onerror', function (original) {
1209
+ const onerror = function (msg, url, line, col, err) {
1210
+ client.logger.debug('window.onerror callback invoked', arguments);
1211
+ if (ignoreOnError > 0) {
1212
+ client.logger.debug('Ignoring window.onerror (error likely reported earlier)', arguments);
1213
+ ignoreOnError -= 1;
1214
+ return;
1215
+ }
1216
+ // See https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onerror#Notes
1217
+ if (line === 0 && /Script error\.?/.test(msg)) {
1218
+ if (client.config.enableUncaught) {
1219
+ // Log only if the user wants to report uncaught errors
1220
+ client.logger.warn('Ignoring cross-domain script error: enable CORS to track these types of errors', arguments);
1221
+ }
1222
+ return;
1223
+ }
1224
+ const notice = makeNotice(err);
1225
+ if (!notice.name) {
1226
+ notice.name = 'window.onerror';
1227
+ }
1228
+ if (!notice.message) {
1229
+ notice.message = msg;
1230
+ }
1231
+ if (!notice.stack) {
1232
+ // Simulate v8 stack
1233
+ notice.stack = [notice.message, '\n at ? (', url || 'unknown', ':', line || 0, ':', col || 0, ')'].join('');
1234
+ }
1235
+ client.addBreadcrumb((notice.name === 'window.onerror' || !notice.name) ? 'window.onerror' : `window.onerror: ${notice.name}`, {
1236
+ category: 'error',
1237
+ metadata: {
1238
+ name: notice.name,
1239
+ message: notice.message,
1240
+ stack: notice.stack
1241
+ }
1242
+ });
1243
+ if (client.config.enableUncaught) {
1244
+ client.notify(notice);
1245
+ }
1246
+ };
1247
+ return function (msg, url, line, col, err) {
1248
+ onerror(msg, url, line, col, err);
1249
+ if (typeof original === 'function') {
1250
+ return original.apply(window, arguments);
1251
+ }
1252
+ return false;
1253
+ };
1254
+ });
1255
+ }
1256
+ };
1257
+ }
1258
+ onerror.onError = onError;
1259
+
1260
+ var onunhandledrejection = {};
1261
+
1262
+ Object.defineProperty(onunhandledrejection, "__esModule", { value: true });
1263
+ /* eslint-disable prefer-rest-params */
1264
+ const core_1$5 = src;
1265
+ const { instrument: instrument$3 } = core_1$5.Util;
1266
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1267
+ function default_1$3(_window = window) {
1268
+ return {
1269
+ load: (client) => {
1270
+ if (!client.config.enableUnhandledRejection) {
1271
+ return;
1272
+ }
1273
+ instrument$3(_window, 'onunhandledrejection', function (original) {
1274
+ // See https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event
1275
+ function onunhandledrejection(promiseRejectionEvent) {
1276
+ var _a;
1277
+ client.logger.debug('window.onunhandledrejection callback invoked', arguments);
1278
+ if (!client.config.enableUnhandledRejection) {
1279
+ return;
1280
+ }
1281
+ const { reason } = promiseRejectionEvent;
1282
+ if (reason instanceof Error) {
1283
+ // simulate v8 stack
1284
+ // const fileName = reason.fileName || 'unknown'
1285
+ // const lineNumber = reason.lineNumber || 0
1286
+ const fileName = 'unknown';
1287
+ const lineNumber = 0;
1288
+ const stackFallback = `${reason.message}\n at ? (${fileName}:${lineNumber})`;
1289
+ const stack = reason.stack || stackFallback;
1290
+ const err = {
1291
+ name: reason.name,
1292
+ message: `UnhandledPromiseRejectionWarning: ${reason}`,
1293
+ stack
1294
+ };
1295
+ client.addBreadcrumb(`window.onunhandledrejection: ${err.name}`, {
1296
+ category: 'error',
1297
+ metadata: err
1298
+ });
1299
+ client.notify(err);
1300
+ return;
1301
+ }
1302
+ const message = typeof reason === 'string' ? reason : ((_a = JSON.stringify(reason)) !== null && _a !== void 0 ? _a : 'Unspecified reason');
1303
+ client.notify({
1304
+ name: 'window.onunhandledrejection',
1305
+ message: `UnhandledPromiseRejectionWarning: ${message}`
1306
+ });
1307
+ }
1308
+ return function (promiseRejectionEvent) {
1309
+ onunhandledrejection(promiseRejectionEvent);
1310
+ if (typeof original === 'function') {
1311
+ original.apply(this, arguments);
1312
+ }
1313
+ };
1314
+ });
1315
+ }
1316
+ };
1317
+ }
1318
+ onunhandledrejection.default = default_1$3;
1319
+
1320
+ var breadcrumbs = {};
1321
+
1322
+ Object.defineProperty(breadcrumbs, "__esModule", { value: true });
1323
+ /* eslint-disable prefer-rest-params */
1324
+ const core_1$4 = src;
1325
+ const util_1$1 = util;
1326
+ const { sanitize: sanitize$1, instrument: instrument$2 } = core_1$4.Util;
1327
+ function default_1$2(_window = window) {
1328
+ return {
1329
+ load: (client) => {
1330
+ function breadcrumbsEnabled(type) {
1331
+ if (client.config.breadcrumbsEnabled === true) {
1332
+ return true;
1333
+ }
1334
+ if (type) {
1335
+ return client.config.breadcrumbsEnabled[type] === true;
1336
+ }
1337
+ return client.config.breadcrumbsEnabled !== false;
1338
+ }
1339
+ // Breadcrumbs: instrument console
1340
+ (function () {
1341
+ if (!breadcrumbsEnabled('console')) {
1342
+ return;
1343
+ }
1344
+ function inspectArray(obj) {
1345
+ if (!Array.isArray(obj)) {
1346
+ return '';
1347
+ }
1348
+ return obj.map(value => {
1349
+ try {
1350
+ return String(value);
1351
+ }
1352
+ catch (e) {
1353
+ return '[unknown]';
1354
+ }
1355
+ }).join(' ');
1356
+ }
1357
+ ['debug', 'info', 'warn', 'error', 'log'].forEach(level => {
1358
+ instrument$2(_window.console, level, function (original) {
1359
+ return function () {
1360
+ const args = Array.prototype.slice.call(arguments);
1361
+ const message = inspectArray(args);
1362
+ const opts = {
1363
+ category: 'log',
1364
+ metadata: {
1365
+ level: level,
1366
+ arguments: sanitize$1(args, 3)
1367
+ }
1368
+ };
1369
+ client.addBreadcrumb(message, opts);
1370
+ if (typeof original === 'function') {
1371
+ Function.prototype.apply.call(original, _window.console, arguments);
1372
+ }
1373
+ };
1374
+ });
1375
+ });
1376
+ })();
1377
+ // Breadcrumbs: instrument click events
1378
+ (function () {
1379
+ if (!breadcrumbsEnabled('dom')) {
1380
+ return;
1381
+ }
1382
+ _window.addEventListener('click', (event) => {
1383
+ let message, selector, text;
1384
+ try {
1385
+ message = (0, util_1$1.stringNameOfElement)(event.target);
1386
+ selector = (0, util_1$1.stringSelectorOfElement)(event.target);
1387
+ text = (0, util_1$1.stringTextOfElement)(event.target);
1388
+ }
1389
+ catch (e) {
1390
+ message = 'UI Click';
1391
+ selector = '[unknown]';
1392
+ text = '[unknown]';
1393
+ }
1394
+ // There's nothing to display
1395
+ if (message.length === 0) {
1396
+ return;
1397
+ }
1398
+ client.addBreadcrumb(message, {
1399
+ category: 'ui.click',
1400
+ metadata: {
1401
+ selector,
1402
+ text,
1403
+ event
1404
+ }
1405
+ });
1406
+ }, true);
1407
+ })();
1408
+ // Breadcrumbs: instrument XMLHttpRequest
1409
+ (function () {
1410
+ if (!breadcrumbsEnabled('network')) {
1411
+ return;
1412
+ }
1413
+ // -- On xhr.open: capture initial metadata
1414
+ instrument$2(XMLHttpRequest.prototype, 'open', function (original) {
1415
+ return function () {
1416
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
1417
+ const xhr = this;
1418
+ const url = arguments[1];
1419
+ const method = typeof arguments[0] === 'string' ? arguments[0].toUpperCase() : arguments[0];
1420
+ const message = `${method} ${(0, util_1$1.localURLPathname)(url)}`;
1421
+ this.__hb_xhr = {
1422
+ type: 'xhr',
1423
+ method,
1424
+ url,
1425
+ message
1426
+ };
1427
+ if (typeof original === 'function') {
1428
+ original.apply(xhr, arguments);
1429
+ }
1430
+ };
1431
+ });
1432
+ // -- On xhr.send: set up xhr.onreadystatechange to report breadcrumb
1433
+ instrument$2(XMLHttpRequest.prototype, 'send', function (original) {
1434
+ return function () {
1435
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
1436
+ const xhr = this;
1437
+ function onreadystatechangeHandler() {
1438
+ if (xhr.readyState === 4) {
1439
+ let message;
1440
+ if (xhr.__hb_xhr) {
1441
+ xhr.__hb_xhr.status_code = xhr.status;
1442
+ message = xhr.__hb_xhr.message;
1443
+ delete xhr.__hb_xhr.message;
1444
+ }
1445
+ client.addBreadcrumb(message || 'XMLHttpRequest', {
1446
+ category: 'request',
1447
+ metadata: xhr.__hb_xhr
1448
+ });
1449
+ }
1450
+ }
1451
+ if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') {
1452
+ instrument$2(xhr, 'onreadystatechange', function (original) {
1453
+ return function () {
1454
+ onreadystatechangeHandler();
1455
+ if (typeof original === 'function') {
1456
+ // eslint-disable-next-line prefer-rest-params
1457
+ original.apply(this, arguments);
1458
+ }
1459
+ };
1460
+ });
1461
+ }
1462
+ else {
1463
+ xhr.onreadystatechange = onreadystatechangeHandler;
1464
+ }
1465
+ if (typeof original === 'function') {
1466
+ // eslint-disable-next-line prefer-rest-params
1467
+ original.apply(xhr, arguments);
1468
+ }
1469
+ };
1470
+ });
1471
+ })();
1472
+ // Breadcrumbs: instrument fetch
1473
+ (function () {
1474
+ if (!breadcrumbsEnabled('network')) {
1475
+ return;
1476
+ }
1477
+ if (!(0, util_1$1.nativeFetch)()) {
1478
+ // Polyfills use XHR.
1479
+ return;
1480
+ }
1481
+ instrument$2(_window, 'fetch', function (original) {
1482
+ return function () {
1483
+ // eslint-disable-next-line prefer-rest-params
1484
+ const input = arguments[0];
1485
+ let method = 'GET';
1486
+ let url;
1487
+ if (typeof input === 'string') {
1488
+ url = input;
1489
+ }
1490
+ else if ('Request' in _window && input instanceof Request) {
1491
+ url = input.url;
1492
+ if (input.method) {
1493
+ method = input.method;
1494
+ }
1495
+ }
1496
+ else {
1497
+ url = String(input);
1498
+ }
1499
+ if (arguments[1] && arguments[1].method) {
1500
+ method = arguments[1].method;
1501
+ }
1502
+ if (typeof method === 'string') {
1503
+ method = method.toUpperCase();
1504
+ }
1505
+ const message = `${method} ${(0, util_1$1.localURLPathname)(url)}`;
1506
+ const metadata = {
1507
+ type: 'fetch',
1508
+ method,
1509
+ url
1510
+ };
1511
+ return original
1512
+ .apply(this, arguments)
1513
+ .then(function (response) {
1514
+ metadata['status_code'] = response.status;
1515
+ client.addBreadcrumb(message, {
1516
+ category: 'request',
1517
+ metadata
1518
+ });
1519
+ return response;
1520
+ })
1521
+ .catch(function (error) {
1522
+ client.addBreadcrumb('fetch error', {
1523
+ category: 'error',
1524
+ metadata
1525
+ });
1526
+ throw error;
1527
+ });
1528
+ };
1529
+ });
1530
+ })();
1531
+ // Breadcrumbs: instrument navigation
1532
+ (function () {
1533
+ if (!breadcrumbsEnabled('navigation')) {
1534
+ return;
1535
+ }
1536
+ // The last known href of the current page
1537
+ let lastHref = _window.location.href;
1538
+ function recordUrlChange(from, to) {
1539
+ lastHref = to;
1540
+ client.addBreadcrumb('Page changed', {
1541
+ category: 'navigation',
1542
+ metadata: {
1543
+ from,
1544
+ to
1545
+ }
1546
+ });
1547
+ }
1548
+ // https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate
1549
+ instrument$2(_window, 'onpopstate', function (original) {
1550
+ return function () {
1551
+ recordUrlChange(lastHref, _window.location.href);
1552
+ if (original) {
1553
+ return original.apply(this, arguments);
1554
+ }
1555
+ };
1556
+ });
1557
+ // https://developer.mozilla.org/en-US/docs/Web/API/History/pushState
1558
+ // https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState
1559
+ function historyWrapper(original) {
1560
+ return function () {
1561
+ const url = arguments.length > 2 ? arguments[2] : undefined;
1562
+ if (url) {
1563
+ recordUrlChange(lastHref, String(url));
1564
+ }
1565
+ return original.apply(this, arguments);
1566
+ };
1567
+ }
1568
+ instrument$2(_window.history, 'pushState', historyWrapper);
1569
+ instrument$2(_window.history, 'replaceState', historyWrapper);
1570
+ })();
1571
+ }
1572
+ };
1573
+ }
1574
+ breadcrumbs.default = default_1$2;
1575
+
1576
+ var timers = {};
1577
+
1578
+ Object.defineProperty(timers, "__esModule", { value: true });
1579
+ /* eslint-disable prefer-rest-params */
1580
+ const core_1$3 = src;
1581
+ const { instrument: instrument$1 } = core_1$3.Util;
1582
+ function default_1$1(_window = window) {
1583
+ return {
1584
+ load: (client) => {
1585
+ // Wrap timers
1586
+ (function () {
1587
+ function instrumentTimer(wrapOpts) {
1588
+ return function (original) {
1589
+ // See https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
1590
+ return function (func, delay) {
1591
+ if (typeof func === 'function') {
1592
+ const args = Array.prototype.slice.call(arguments, 2);
1593
+ func = client.__wrap(func, wrapOpts);
1594
+ return original(function () {
1595
+ func(...args);
1596
+ }, delay);
1597
+ }
1598
+ else {
1599
+ return original(func, delay);
1600
+ }
1601
+ };
1602
+ };
1603
+ }
1604
+ instrument$1(_window, 'setTimeout', instrumentTimer({ component: 'setTimeout' }));
1605
+ instrument$1(_window, 'setInterval', instrumentTimer({ component: 'setInterval' }));
1606
+ })();
1607
+ }
1608
+ };
1609
+ }
1610
+ timers.default = default_1$1;
1611
+
1612
+ var event_listeners = {};
1613
+
1614
+ Object.defineProperty(event_listeners, "__esModule", { value: true });
1615
+ const core_1$2 = src;
1616
+ const { instrument } = core_1$2.Util;
1617
+ function default_1(_window = window) {
1618
+ return {
1619
+ load: (client) => {
1620
+ // Wrap event listeners
1621
+ // Event targets borrowed from bugsnag-js:
1622
+ // See https://github.com/bugsnag/bugsnag-js/blob/d55af916a4d3c7757f979d887f9533fe1a04cc93/src/bugsnag.js#L542
1623
+ const targets = ['EventTarget', 'Window', 'Node', 'ApplicationCache', 'AudioTrackList', 'ChannelMergerNode', 'CryptoOperation', 'EventSource', 'FileReader', 'HTMLUnknownElement', 'IDBDatabase', 'IDBRequest', 'IDBTransaction', 'KeyOperation', 'MediaController', 'MessagePort', 'ModalWindow', 'Notification', 'SVGElementInstance', 'Screen', 'TextTrack', 'TextTrackCue', 'TextTrackList', 'WebSocket', 'WebSocketWorker', 'Worker', 'XMLHttpRequest', 'XMLHttpRequestEventTarget', 'XMLHttpRequestUpload'];
1624
+ targets.forEach(function (prop) {
1625
+ const prototype = _window[prop] && _window[prop].prototype;
1626
+ if (prototype && Object.prototype.hasOwnProperty.call(prototype, 'addEventListener')) {
1627
+ instrument(prototype, 'addEventListener', function (original) {
1628
+ const wrapOpts = { component: `${prop}.prototype.addEventListener` };
1629
+ // See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
1630
+ return function (type, listener, useCapture, wantsUntrusted) {
1631
+ try {
1632
+ if (listener && listener.handleEvent != null) {
1633
+ listener.handleEvent = client.__wrap(listener.handleEvent, wrapOpts);
1634
+ }
1635
+ }
1636
+ catch (e) {
1637
+ // Ignore 'Permission denied to access property "handleEvent"' errors.
1638
+ client.logger.error(e);
1639
+ }
1640
+ return original.call(this, type, client.__wrap(listener, wrapOpts), useCapture, wantsUntrusted);
1641
+ };
1642
+ });
1643
+ instrument(prototype, 'removeEventListener', function (original) {
1644
+ return function (type, listener, useCapture, wantsUntrusted) {
1645
+ original.call(this, type, listener, useCapture, wantsUntrusted);
1646
+ return original.call(this, type, client.__wrap(listener), useCapture, wantsUntrusted);
1647
+ };
1648
+ });
1649
+ }
1650
+ });
1651
+ }
1652
+ };
1653
+ }
1654
+ event_listeners.default = default_1;
1655
+
1656
+ var transport = {};
1657
+
1658
+ Object.defineProperty(transport, "__esModule", { value: true });
1659
+ transport.BrowserTransport = void 0;
1660
+ const core_1$1 = src;
1661
+ const { sanitize } = core_1$1.Util;
1662
+ class BrowserTransport {
1663
+ send(options, payload) {
1664
+ return new Promise((resolve, reject) => {
1665
+ try {
1666
+ const x = new XMLHttpRequest();
1667
+ x.open(options.method, options.endpoint, options.async);
1668
+ if (Object.keys(options.headers || []).length) {
1669
+ for (const i in options.headers) {
1670
+ if (typeof options.headers[i] !== 'undefined') {
1671
+ x.setRequestHeader(i, String(options.headers[i]));
1672
+ }
1673
+ }
1674
+ }
1675
+ x.send(payload ? JSON.stringify(sanitize(payload, options.maxObjectDepth)) : undefined);
1676
+ x.onload = () => resolve({ statusCode: x.status, body: x.response });
1677
+ }
1678
+ catch (err) {
1679
+ reject(err);
1680
+ }
1681
+ });
1682
+ }
1683
+ }
1684
+ transport.BrowserTransport = BrowserTransport;
1685
+
1686
+ var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
1687
+ return (mod && mod.__esModule) ? mod : { "default": mod };
1688
+ };
1689
+ Object.defineProperty(browser, "__esModule", { value: true });
1690
+ const core_1 = src;
1691
+ const util_1 = util;
1692
+ const onerror_1 = onerror;
1693
+ const onunhandledrejection_1 = __importDefault(onunhandledrejection);
1694
+ const breadcrumbs_1 = __importDefault(breadcrumbs);
1695
+ const timers_1 = __importDefault(timers);
1696
+ const event_listeners_1 = __importDefault(event_listeners);
1697
+ const transport_1 = transport;
1698
+ const { merge, filter, objectIsExtensible } = core_1.Util;
1699
+ class Honeybadger extends core_1.Client {
1700
+ constructor(opts = {}) {
1701
+ super(Object.assign({ async: true, maxErrors: null, projectRoot: window.location.protocol + '//' + window.location.host }, opts), new transport_1.BrowserTransport());
1702
+ /** @internal */
1703
+ this.__errorsSent = 0;
1704
+ /** @internal */
1705
+ this.__lastWrapErr = undefined;
1706
+ /** @internal */
1707
+ this.__beforeNotifyHandlers = [
1708
+ (notice) => {
1709
+ if (this.__exceedsMaxErrors()) {
1710
+ this.logger.debug('Dropping notice: max errors exceeded', notice);
1711
+ return false;
1712
+ }
1713
+ if (notice && !notice.url) {
1714
+ notice.url = document.URL;
1715
+ }
1716
+ this.__incrementErrorsCount();
1717
+ return true;
1718
+ }
1719
+ ];
1720
+ }
1721
+ configure(opts = {}) {
1722
+ return super.configure(opts);
1723
+ }
1724
+ resetMaxErrors() {
1725
+ return (this.__errorsSent = 0);
1726
+ }
1727
+ factory(opts) {
1728
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1729
+ return new Honeybadger(opts);
1730
+ }
1731
+ checkIn(_id) {
1732
+ throw new Error('Honeybadger.checkIn() is not supported on the browser');
1733
+ }
1734
+ /** @internal */
1735
+ __buildPayload(notice) {
1736
+ const cgiData = {
1737
+ HTTP_USER_AGENT: undefined,
1738
+ HTTP_REFERER: undefined,
1739
+ HTTP_COOKIE: undefined
1740
+ };
1741
+ cgiData.HTTP_USER_AGENT = navigator.userAgent;
1742
+ if (document.referrer.match(/\S/)) {
1743
+ cgiData.HTTP_REFERER = document.referrer;
1744
+ }
1745
+ let cookiesObject;
1746
+ if (typeof notice.cookies === 'string') {
1747
+ cookiesObject = (0, util_1.decodeCookie)(notice.cookies);
1748
+ }
1749
+ else {
1750
+ cookiesObject = notice.cookies;
1751
+ }
1752
+ if (cookiesObject) {
1753
+ cgiData.HTTP_COOKIE = (0, util_1.encodeCookie)(filter(cookiesObject, this.config.filters));
1754
+ }
1755
+ const payload = super.__buildPayload(notice);
1756
+ payload.request.cgi_data = merge(cgiData, payload.request.cgi_data);
1757
+ return payload;
1758
+ }
1759
+ /**
1760
+ * wrap always returns the same function so that callbacks can be removed via
1761
+ * removeEventListener.
1762
+ * @internal
1763
+ */
1764
+ __wrap(f, opts = {}) {
1765
+ const func = f;
1766
+ if (!opts) {
1767
+ opts = {};
1768
+ }
1769
+ try {
1770
+ if (typeof func !== 'function') {
1771
+ return func;
1772
+ }
1773
+ if (!objectIsExtensible(func)) {
1774
+ return func;
1775
+ }
1776
+ if (!func.___hb) {
1777
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
1778
+ const client = this;
1779
+ func.___hb = function () {
1780
+ if (util_1.preferCatch) {
1781
+ try {
1782
+ // eslint-disable-next-line prefer-rest-params
1783
+ return func.apply(this, arguments);
1784
+ }
1785
+ catch (err) {
1786
+ if (client.__lastWrapErr === err) {
1787
+ throw (err);
1788
+ }
1789
+ client.__lastWrapErr = err;
1790
+ (0, onerror_1.ignoreNextOnError)();
1791
+ client.addBreadcrumb(opts.component ? `${opts.component}: ${err.name}` : err.name, {
1792
+ category: 'error',
1793
+ metadata: {
1794
+ message: err.message,
1795
+ name: err.name,
1796
+ stack: err.stack
1797
+ }
1798
+ });
1799
+ if (client.config.enableUncaught) {
1800
+ client.notify(err);
1801
+ }
1802
+ throw (err);
1803
+ }
1804
+ }
1805
+ else {
1806
+ // eslint-disable-next-line prefer-rest-params
1807
+ return func.apply(this, arguments);
1808
+ }
1809
+ };
1810
+ }
1811
+ func.___hb.___hb = func.___hb;
1812
+ return func.___hb;
1813
+ }
1814
+ catch (_e) {
1815
+ return func;
1816
+ }
1817
+ }
1818
+ /** @internal */
1819
+ __incrementErrorsCount() {
1820
+ return this.__errorsSent++;
1821
+ }
1822
+ /** @internal */
1823
+ __exceedsMaxErrors() {
1824
+ return this.config.maxErrors && this.__errorsSent >= this.config.maxErrors;
1825
+ }
1826
+ }
1827
+ var _default = browser.default = new Honeybadger({
1828
+ __plugins: [
1829
+ (0, onerror_1.onError)(),
1830
+ (0, onunhandledrejection_1.default)(),
1831
+ (0, timers_1.default)(),
1832
+ (0, event_listeners_1.default)(),
1833
+ (0, breadcrumbs_1.default)()
1834
+ ]
1835
+ });
1836
+
1837
+ return _default;
1741
1838
 
1742
1839
  }));
1743
1840
  //# sourceMappingURL=honeybadger.js.map