@honeybadger-io/js 5.1.5-alpha-2 → 5.1.7

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