rollbar
Version:
Effortlessly track and debug errors in your JavaScript applications with Rollbar. This package includes advanced error tracking features and an intuitive interface to help you identify and fix issues more quickly.
1,424 lines (1,385 loc) • 187 kB
JavaScript
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"default": () => (/* binding */ server_rollbar)
});
;// external "os"
const external_os_namespaceObject = require("os");
;// external "url"
const external_url_namespaceObject = require("url");
;// external "util"
const external_util_namespaceObject = require("util");
;// external "json-stringify-safe"
const external_json_stringify_safe_namespaceObject = require("json-stringify-safe");
;// ./src/utility.js
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
/*
* isType - Given a Javascript value and a string, returns true if the type of the value matches the
* given string.
*
* @param x - any value
* @param t - a lowercase string containing one of the following type names:
* - undefined
* - null
* - error
* - number
* - boolean
* - string
* - symbol
* - function
* - object
* - array
* @returns true if x is of type t, otherwise false
*/
function isType(x, t) {
return t === typeName(x);
}
/*
* typeName - Given a Javascript value, returns the type of the object as a string
*/
function typeName(x) {
var name = _typeof(x);
if (name !== 'object') {
return name;
}
if (!x) {
return 'null';
}
if (x instanceof Error) {
return 'error';
}
return {}.toString.call(x).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
/* isFunction - a convenience function for checking if a value is a function
*
* @param f - any value
* @returns true if f is a function, otherwise false
*/
function isFunction(f) {
return isType(f, 'function');
}
/* isNativeFunction - a convenience function for checking if a value is a native JS function
*
* @param f - any value
* @returns true if f is a native JS function, otherwise false
*/
function isNativeFunction(f) {
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
var funcMatchString = Function.prototype.toString.call(Object.prototype.hasOwnProperty).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?');
var reIsNative = RegExp('^' + funcMatchString + '$');
return isObject(f) && reIsNative.test(f);
}
/* isObject - Checks if the argument is an object
*
* @param value - any value
* @returns true is value is an object function is an object)
*/
function isObject(value) {
return value != null && (_typeof(value) == 'object' || typeof value == 'function');
}
/* hasOwn - safe helper around Object.hasOwnProperty */
function hasOwn(obj, prop) {
if (obj == null) {
return false;
}
if (Object.hasOwn) {
return Object.hasOwn(obj, prop);
}
return Object.prototype.hasOwnProperty.call(obj, prop);
}
/* isString - Checks if the argument is a string
*
* @param value - any value
* @returns true if value is a string
*/
function isString(value) {
return typeof value === 'string' || value instanceof String;
}
/**
* isFiniteNumber - determines whether the passed value is a finite number
*
* @param {*} n - any value
* @returns true if value is a finite number
*/
function isFiniteNumber(n) {
return Number.isFinite(n);
}
/*
* isIterable - convenience function for checking if a value can be iterated, essentially
* whether it is an object or an array.
*
* @param i - any value
* @returns true if i is an object or an array as determined by `typeName`
*/
function isIterable(i) {
var type = typeName(i);
return type === 'object' || type === 'array';
}
/*
* isError - convenience function for checking if a value is of an error type
*
* @param e - any value
* @returns true if e is an error
*/
function isError(e) {
// Detect both Error and Firefox Exception type
return isType(e, 'error') || isType(e, 'exception');
}
/* isPromise - a convenience function for checking if a value is a promise
*
* @param p - any value
* @returns true if f is a function, otherwise false
*/
function isPromise(p) {
return isObject(p) && isType(p.then, 'function');
}
/**
* isBrowser - a convenience function for checking if the code is running in a browser
*
* @returns true if the code is running in a browser environment
*/
function isBrowser() {
return typeof window !== 'undefined';
}
function isRequestObject(input) {
return typeof Request !== 'undefined' && input instanceof Request;
}
function redact() {
return '********';
}
// from http://stackoverflow.com/a/8809472/1138191
function uuid4() {
var d = now();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : r & 0x7 | 0x8).toString(16);
});
return uuid;
}
var LEVELS = {
debug: 0,
info: 1,
warning: 2,
error: 3,
critical: 4
};
function sanitizeHref(url) {
try {
var urlObject = new URL(url);
if (urlObject.password) {
urlObject.password = redact();
}
if (urlObject.search) {
urlObject.search = redact();
}
return urlObject.toString();
} catch (_) {
return url; // Return original URL if parsing fails
}
}
function sanitizeUrl(url) {
var baseUrlParts = parseUri(url);
if (!baseUrlParts) {
return '(unknown)';
}
// remove a trailing # if there is no anchor
if (baseUrlParts.anchor === '') {
baseUrlParts.source = baseUrlParts.source.replace('#', '');
}
url = baseUrlParts.source.replace('?' + baseUrlParts.query, '');
return url;
}
var parseUriOptions = {
strictMode: false,
key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'],
q: {
name: 'queryKey',
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:/?#]*)(?::(\d*))?))?((((?:[^?#/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:@]+:[^:@/]*@)([^:/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#/]*\.[^?#/.]+(?:[?#]|$)))*\/?)?([^?#/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};
function parseUri(str) {
if (!isType(str, 'string')) {
return undefined;
}
var o = parseUriOptions;
var m = o.parser[o.strictMode ? 'strict' : 'loose'].exec(str);
var uri = {};
for (var i = 0, l = o.key.length; i < l; ++i) {
uri[o.key[i]] = m[i] || '';
}
uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if ($1) {
uri[o.q.name][$1] = $2;
}
});
return uri;
}
function addParamsAndAccessTokenToPath(accessToken, options, params) {
params = params || {};
params.access_token = accessToken;
var paramsArray = [];
var k;
for (k in params) {
if (Object.prototype.hasOwnProperty.call(params, k)) {
paramsArray.push([k, params[k]].join('='));
}
}
var query = '?' + paramsArray.sort().join('&');
options = options || {};
options.path = options.path || '';
var qs = options.path.indexOf('?');
var h = options.path.indexOf('#');
var p;
if (qs !== -1 && (h === -1 || h > qs)) {
p = options.path;
options.path = p.substring(0, qs) + query + '&' + p.substring(qs + 1);
} else {
if (h !== -1) {
p = options.path;
options.path = p.substring(0, h) + query + p.substring(h);
} else {
options.path = options.path + query;
}
}
}
function formatUrl(u, protocol) {
protocol = protocol || u.protocol;
if (!protocol && u.port) {
if (u.port === 80) {
protocol = 'http:';
} else if (u.port === 443) {
protocol = 'https:';
}
}
protocol = protocol || 'https:';
if (!u.hostname) {
return null;
}
var result = protocol + '//' + u.hostname;
if (u.port) {
result = result + ':' + u.port;
}
if (u.path) {
result = result + u.path;
}
return result;
}
function stringify(obj, backup) {
var value, error;
try {
value = JSON.stringify(obj);
} catch (jsonError) {
if (backup && isFunction(backup)) {
try {
value = backup(obj);
} catch (backupError) {
error = backupError;
}
} else {
error = jsonError;
}
}
return {
error: error,
value: value
};
}
function maxByteSize(string) {
// The transport will use utf-8, so assume utf-8 encoding.
//
// This minimal implementation will accurately count bytes for all UCS-2 and
// single code point UTF-16. If presented with multi code point UTF-16,
// which should be rare, it will safely overcount, not undercount.
//
// While robust utf-8 encoders exist, this is far smaller and far more performant.
// For quickly counting payload size for truncation, smaller is better.
var count = 0;
var length = string.length;
for (var i = 0; i < length; i++) {
var code = string.charCodeAt(i);
if (code < 128) {
// up to 7 bits
count = count + 1;
} else if (code < 2048) {
// up to 11 bits
count = count + 2;
} else if (code < 65536) {
// up to 16 bits
count = count + 3;
}
}
return count;
}
function jsonParse(s) {
var value, error;
try {
value = JSON.parse(s);
} catch (e) {
error = e;
}
return {
error: error,
value: value
};
}
function makeUnhandledStackInfo(message, url, lineno, colno, error, mode, backupMessage, errorParser) {
var location = {
url: url || '',
line: lineno,
column: colno
};
location.func = errorParser.guessFunctionName(location.url, location.line);
location.context = errorParser.gatherContext(location.url, location.line);
var href = typeof document !== 'undefined' && document && document.location && document.location.href;
var useragent = typeof window !== 'undefined' && window && window.navigator && window.navigator.userAgent;
return {
mode: mode,
message: error ? String(error) : message || backupMessage,
url: href,
stack: [location],
useragent: useragent
};
}
function wrapCallback(logger, f) {
return function (err, resp) {
try {
f(err, resp);
} catch (e) {
logger.error(e);
}
};
}
function nonCircularClone(obj) {
var seen = [obj];
function clone(obj, seen) {
var value,
name,
newSeen,
result = {};
try {
for (name in obj) {
value = obj[name];
if (value && (isType(value, 'object') || isType(value, 'array'))) {
if (seen.includes(value)) {
result[name] = 'Removed circular reference: ' + typeName(value);
} else {
newSeen = seen.slice();
newSeen.push(value);
result[name] = clone(value, newSeen);
}
continue;
}
result[name] = value;
}
} catch (e) {
result = 'Failed cloning custom data: ' + e.message;
}
return result;
}
return clone(obj, seen);
}
function createItem(args, logger, notifier, requestKeys, lambdaContext) {
var message, err, custom, callback, request;
var arg;
var extraArgs = [];
var diagnostic = {};
var argTypes = [];
for (var i = 0, l = args.length; i < l; ++i) {
arg = args[i];
var typ = typeName(arg);
argTypes.push(typ);
switch (typ) {
case 'undefined':
break;
case 'string':
if (message) {
extraArgs.push(arg);
} else {
message = arg;
}
break;
case 'function':
callback = wrapCallback(logger, arg);
break;
case 'date':
extraArgs.push(arg);
break;
case 'error':
case 'domexception':
case 'exception':
// Firefox Exception type
if (err) {
extraArgs.push(arg);
} else {
err = arg;
}
break;
case 'object':
case 'array':
if (arg instanceof Error || typeof DOMException !== 'undefined' && arg instanceof DOMException) {
if (err) {
extraArgs.push(arg);
} else {
err = arg;
}
break;
}
if (requestKeys && typ === 'object' && !request) {
for (var j = 0, len = requestKeys.length; j < len; ++j) {
if (arg[requestKeys[j]] !== undefined) {
request = arg;
break;
}
}
if (request) {
break;
}
}
if (custom) {
extraArgs.push(arg);
} else {
custom = arg;
}
break;
default:
if (arg instanceof Error || typeof DOMException !== 'undefined' && arg instanceof DOMException) {
if (err) {
extraArgs.push(arg);
} else {
err = arg;
}
break;
}
extraArgs.push(arg);
}
}
// if custom is an array this turns it into an object with integer keys
if (custom) custom = nonCircularClone(custom);
if (extraArgs.length > 0) {
if (!custom) custom = nonCircularClone({});
custom.extraArgs = nonCircularClone(extraArgs);
}
var item = {
message: message,
err: err,
custom: custom,
timestamp: now(),
callback: callback,
notifier: notifier,
diagnostic: diagnostic,
uuid: uuid4()
};
item.data = item.data || {};
setCustomItemKeys(item, custom);
if (requestKeys && request) {
item.request = request;
}
if (lambdaContext) {
item.lambdaContext = lambdaContext;
}
item._originalArgs = args;
item.diagnostic.original_arg_types = argTypes;
return item;
}
function setCustomItemKeys(item, custom) {
if (custom && custom.level !== undefined) {
item.level = custom.level;
delete custom.level;
}
if (custom && custom.skipFrames !== undefined) {
item.skipFrames = custom.skipFrames;
delete custom.skipFrames;
}
}
function addErrorContext(item, errors) {
var custom = item.data.custom || {};
var contextAdded = false;
try {
var _iterator = _createForOfIteratorHelper(errors),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var error = _step.value;
if (hasOwn(error, 'rollbarContext')) {
custom = merge(custom, nonCircularClone(error.rollbarContext));
contextAdded = true;
}
}
// Avoid adding an empty object to the data.
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
if (contextAdded) {
item.data.custom = custom;
}
} catch (e) {
item.diagnostic.error_context = 'Failed: ' + e.message;
}
}
var TELEMETRY_TYPES = ['log', 'network', 'dom', 'navigation', 'error', 'manual'];
var TELEMETRY_LEVELS = ['critical', 'error', 'warning', 'info', 'debug'];
function arrayIncludes(arr, val) {
var _iterator2 = _createForOfIteratorHelper(arr),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var entry = _step2.value;
if (entry === val) {
return true;
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
return false;
}
function createTelemetryEvent(args) {
var type, metadata, level;
var arg;
for (var i = 0, l = args.length; i < l; ++i) {
arg = args[i];
var typ = typeName(arg);
switch (typ) {
case 'string':
if (!type && arrayIncludes(TELEMETRY_TYPES, arg)) {
type = arg;
} else if (!level && arrayIncludes(TELEMETRY_LEVELS, arg)) {
level = arg;
}
break;
case 'object':
metadata = arg;
break;
default:
break;
}
}
var event = {
type: type || 'manual',
metadata: metadata || {},
level: level
};
return event;
}
function addItemAttributes(itemData, attributes) {
itemData.attributes = itemData.attributes || [];
var _iterator3 = _createForOfIteratorHelper(attributes),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var a = _step3.value;
if (a.value === undefined) {
continue;
}
itemData.attributes.push(a);
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
}
/*
* get - given an obj/array and a keypath, return the value at that keypath or
* undefined if not possible.
*
* @param obj - an object or array
* @param path - a string of keys separated by '.' such as 'plugin.jquery.0.message'
* which would correspond to 42 in `{plugin: {jquery: [{message: 42}]}}`
*/
function get(obj, path) {
if (!obj) {
return undefined;
}
var keys = path.split('.');
var result = obj;
try {
for (var i = 0, len = keys.length; i < len; ++i) {
result = result[keys[i]];
}
} catch (_e) {
result = undefined;
}
return result;
}
function set(obj, path, value) {
if (!obj) {
return;
}
// Prevent prototype pollution by setting the prototype to null.
Object.setPrototypeOf(obj, null);
var keys = path.split('.');
var len = keys.length;
if (len < 1) {
return;
}
if (len === 1) {
obj[keys[0]] = value;
return;
}
try {
var temp = obj[keys[0]] || {};
var replacement = temp;
for (var i = 1; i < len - 1; ++i) {
temp[keys[i]] = temp[keys[i]] || {};
temp = temp[keys[i]];
}
temp[keys[len - 1]] = value;
obj[keys[0]] = replacement;
} catch (_e) {
return;
}
}
function formatArgsAsString(args) {
var i, len, arg;
var result = [];
for (i = 0, len = args.length; i < len; ++i) {
arg = args[i];
switch (typeName(arg)) {
case 'object':
arg = stringify(arg);
arg = arg.error || arg.value;
if (arg.length > 500) {
arg = arg.substr(0, 497) + '...';
}
break;
case 'null':
arg = 'null';
break;
case 'undefined':
arg = 'undefined';
break;
case 'symbol':
arg = arg.toString();
break;
}
result.push(arg);
}
return result.join(' ');
}
function now() {
if (Date.now) {
return Date.now();
}
return Number(new Date());
}
function filterIp(requestData, captureIp) {
if (!requestData || !requestData['user_ip'] || captureIp === true) {
return;
}
var newIp = requestData['user_ip'];
if (!captureIp) {
newIp = null;
} else {
try {
var parts;
if (newIp.indexOf('.') !== -1) {
parts = newIp.split('.');
parts.pop();
parts.push('0');
newIp = parts.join('.');
} else if (newIp.indexOf(':') !== -1) {
parts = newIp.split(':');
if (parts.length > 2) {
var beginning = parts.slice(0, 3);
var slashIdx = beginning[2].indexOf('/');
if (slashIdx !== -1) {
beginning[2] = beginning[2].substring(0, slashIdx);
}
var terminal = '0000:0000:0000:0000:0000';
newIp = beginning.concat(terminal).join(':');
}
} else {
newIp = null;
}
} catch (_e) {
newIp = null;
}
}
requestData['user_ip'] = newIp;
}
function handleOptions(current, input, payload, logger) {
var result = merge(current, input, payload);
result = updateDeprecatedOptions(result, logger);
if (!input || input.overwriteScrubFields) {
return result;
}
if (input.scrubFields) {
result.scrubFields = (current.scrubFields || []).concat(input.scrubFields);
}
return result;
}
function updateDeprecatedOptions(options, logger) {
if (options.hostWhiteList && !options.hostSafeList) {
options.hostSafeList = options.hostWhiteList;
options.hostWhiteList = undefined;
logger && logger.log('hostWhiteList is deprecated. Use hostSafeList.');
}
if (options.hostBlackList && !options.hostBlockList) {
options.hostBlockList = options.hostBlackList;
options.hostBlackList = undefined;
logger && logger.log('hostBlackList is deprecated. Use hostBlockList.');
}
return options;
}
function merge() {
function isPlainObject(obj) {
if (!obj || Object.prototype.toString.call(obj) !== '[object Object]') {
return false;
}
var hasOwnConstructor = hasOwn(obj, 'constructor');
var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn(obj.constructor.prototype, 'isPrototypeOf');
// Not own constructor property must be Object
if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for (key in obj) {
/**/
}
return typeof key === 'undefined' || hasOwn(obj, key);
}
var i,
src,
copy,
clone,
name,
result = Object.create(null),
// no prototype pollution on Object
current = null,
length = arguments.length;
for (i = 0; i < length; i++) {
current = arguments[i];
if (current === null || current === undefined) {
continue;
}
for (name in current) {
src = result[name];
copy = current[name];
if (result !== copy) {
if (copy && isPlainObject(copy)) {
clone = src && isPlainObject(src) ? src : {};
result[name] = merge(clone, copy);
} else if (typeof copy !== 'undefined') {
result[name] = copy;
}
}
}
}
return result;
}
function shouldAddBaggageHeader(options, tracing, url) {
var _options$tracing;
if (!(tracing !== null && tracing !== void 0 && tracing.sessionId) || !url) {
return false;
}
var propagation = options === null || options === void 0 || (_options$tracing = options.tracing) === null || _options$tracing === void 0 ? void 0 : _options$tracing.propagation;
var enabledHeaders = propagation === null || propagation === void 0 ? void 0 : propagation.enabledHeaders;
if (!Array.isArray(enabledHeaders) || !enabledHeaders.includes('baggage')) {
return false;
}
var enabledCorsUrls = propagation === null || propagation === void 0 ? void 0 : propagation.enabledCorsUrls;
if (!Array.isArray(enabledCorsUrls) || enabledCorsUrls.length === 0) {
return false;
}
return enabledCorsUrls.some(function (pattern) {
if (isType(pattern, 'string')) {
return url === pattern;
}
if (isType(pattern, 'regexp')) {
return pattern.test(url);
}
return false;
});
}
function addHeadersToFetch(args, newHeaders) {
var _init;
// Headers may be in the request object or the init object.
// If present in both places, the init object must be used.
//
var init = args[1];
var initHeaders = (_init = init) === null || _init === void 0 ? void 0 : _init.headers;
var reqHeaders = isRequestObject(args[0]) && args[0].headers;
var headers = initHeaders || reqHeaders;
// If headers are not present in either place, they are added to the init object.
// If there is no init object, one must be created and added to args.
if (!headers) {
if (!init) {
args[1] = init = {};
}
headers = init.headers = {};
}
// `headers` may be a Headers object or a plain object.
if (headers instanceof Headers) {
for (var _i = 0, _Object$keys = Object.keys(newHeaders); _i < _Object$keys.length; _i++) {
var key = _Object$keys[_i];
headers.append(key, newHeaders[key]);
}
} else if (isObject(headers)) {
for (var _i2 = 0, _Object$keys2 = Object.keys(newHeaders); _i2 < _Object$keys2.length; _i2++) {
var _key = _Object$keys2[_i2];
headers[_key] = newHeaders[_key];
}
}
}
function getSessionIdFromAsyncLocalStorage(client) {
var storage = client.asyncLocalStorage;
if (!storage || typeof storage.getStore !== 'function') {
return null;
}
var store = storage.getStore();
return (store === null || store === void 0 ? void 0 : store.sessionId) || null;
}
;// ./src/apiUtility.js
function buildPayload(data) {
if (!isType(data.context, 'string')) {
var contextResult = stringify(data.context);
if (contextResult.error) {
data.context = "Error: could not serialize 'context'";
} else {
data.context = contextResult.value || '';
}
if (data.context.length > 255) {
data.context = data.context.substr(0, 255);
}
}
return {
data: data
};
}
function getTransportFromOptions(options, defaults, url) {
var hostname = defaults.hostname;
var protocol = defaults.protocol;
var port = defaults.port;
var path = defaults.path;
var search = defaults.search;
var timeout = options.timeout;
var transport = detectTransport(options);
var proxy = options.proxy;
if (options.endpoint) {
var opts = url.parse(options.endpoint);
hostname = opts.hostname;
protocol = opts.protocol;
port = opts.port;
path = opts.pathname;
search = opts.search;
}
return {
timeout: timeout,
hostname: hostname,
protocol: protocol,
port: port,
path: path,
search: search,
proxy: proxy,
transport: transport
};
}
function detectTransport(options) {
var gWindow = typeof window !== 'undefined' && window || typeof self !== 'undefined' && self;
var transport = options.defaultTransport || 'xhr';
if (typeof gWindow.fetch === 'undefined') transport = 'xhr';
if (typeof gWindow.XMLHttpRequest === 'undefined') transport = 'fetch';
return transport;
}
function apiUtility_transportOptions(transport, method) {
var protocol = transport.protocol || 'https:';
var port = transport.port || (protocol === 'http:' ? 80 : protocol === 'https:' ? 443 : undefined);
var hostname = transport.hostname;
var path = transport.path;
var timeout = transport.timeout;
var transportAPI = transport.transport;
if (transport.search) {
path = path + transport.search;
}
if (transport.proxy) {
path = protocol + '//' + hostname + path;
hostname = transport.proxy.host || transport.proxy.hostname;
port = transport.proxy.port;
protocol = transport.proxy.protocol || protocol;
}
return {
timeout: timeout,
protocol: protocol,
hostname: hostname,
path: path,
port: port,
method: method,
transport: transportAPI
};
}
function appendPathToPath(base, path) {
var baseTrailingSlash = /\/$/.test(base);
var pathBeginningSlash = /^\//.test(path);
if (baseTrailingSlash && pathBeginningSlash) {
path = path.substring(1);
} else if (!baseTrailingSlash && !pathBeginningSlash) {
path = '/' + path;
}
return base + path;
}
;// ./src/api.js
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function api_typeof(o) { "@babel/helpers - typeof"; return api_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, api_typeof(o); }
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == api_typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != api_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != api_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var defaultOptions = {
hostname: 'api.rollbar.com',
path: '/api/1/item/',
search: null,
version: '1',
protocol: 'https:',
port: 443
};
var OTLPDefaultOptions = {
hostname: 'api.rollbar.com',
path: '/api/1/session/',
search: null,
version: '1',
protocol: 'https:',
port: 443
};
/**
* Api encapsulates methods of communicating with the Rollbar API. It is a
* standard interface with some parts implemented differently for server or
* browser contexts. It is an object that should be instantiated when used so
* it can contain non-global options that may be different for another instance
* of RollbarApi.
*/
var Api = /*#__PURE__*/function () {
/**
* @param {Object} options - Configuration supplied from the parent Rollbar instance.
* @param {string} options.accessToken - Token used to authenticate API calls.
* @param {string} [options.endpoint] - Optional fully qualified URL overriding
* the default `https://api.rollbar.com/api/1/item`.
* @param {Object} [options.proxy] - Optional proxy descriptor containing:
* `host`/`hostname` (required), `port`, and `protocol`.
* @param {Object} transport - Adapter implementing `post` and `postJsonPayload`.
* @param {Object} urllib - Minimal URL helper used for option normalization.
* @param {Object} truncation - Optional truncation helper for payload size enforcement.
*/
function Api(options, transport, urllib, truncation) {
_classCallCheck(this, Api);
this.options = options;
this.transport = transport;
this.url = urllib;
this.truncation = truncation;
this.accessToken = options.accessToken;
this.transportOptions = _getTransport(options, urllib);
this.OTLPTransportOptions = _getOTLPTransport(options, urllib);
}
/**
* Wraps transport.post in a Promise to support async/await
*
* @param {Object} options - Options for the API request
* @param {string} options.accessToken - The access token for authentication
* @param {Object} options.transportOptions - Options for the transport
* @param {Object} options.payload - The data payload to send
* @returns {Promise} A promise that resolves with the response or rejects with an error
* @private
*/
return _createClass(Api, [{
key: "_postPromise",
value: function _postPromise(_ref) {
var _this = this;
var accessToken = _ref.accessToken,
options = _ref.options,
payload = _ref.payload,
headers = _ref.headers;
return new Promise(function (resolve, reject) {
_this.transport.post({
accessToken: accessToken,
options: options,
payload: payload,
headers: headers,
callback: function callback(err, resp) {
return err ? reject(err) : resolve(resp);
}
});
});
}
/**
*
* @param data
* @param callback
*/
}, {
key: "postItem",
value: function postItem(data, callback) {
var _this2 = this;
var options = apiUtility_transportOptions(this.transportOptions, 'POST');
var payload = buildPayload(data);
// ensure the network request is scheduled after the current tick.
setTimeout(function () {
_this2.transport.post({
accessToken: _this2.accessToken,
options: options,
payload: payload,
callback: callback
});
}, 0);
}
/**
* Posts spans to the Rollbar API using the session endpoint
*
* @param {Array} payload - The spans to send
* @returns {Promise<Object>} A promise that resolves with the API response
*/
}, {
key: "postSpans",
value: (function () {
var _postSpans = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(payload) {
var headers,
options,
_args = arguments;
return _regenerator().w(function (_context) {
while (1) switch (_context.n) {
case 0:
headers = _args.length > 1 && _args[1] !== undefined ? _args[1] : {};
options = apiUtility_transportOptions(this.OTLPTransportOptions, 'POST');
return _context.a(2, this._postPromise({
accessToken: this.accessToken,
options: options,
payload: payload,
headers: headers
}));
}
}, _callee, this);
}));
function postSpans(_x) {
return _postSpans.apply(this, arguments);
}
return postSpans;
}()
/**
*
* @param data
* @param callback
*/
)
}, {
key: "buildJsonPayload",
value: function buildJsonPayload(data, callback) {
var payload = buildPayload(data);
var stringifyResult;
if (this.truncation) {
stringifyResult = this.truncation.truncate(payload);
} else {
stringifyResult = stringify(payload);
}
if (stringifyResult.error) {
if (callback) {
callback(stringifyResult.error);
}
return null;
}
return stringifyResult.value;
}
/**
*
* @param jsonPayload
* @param callback
*/
}, {
key: "postJsonPayload",
value: function postJsonPayload(jsonPayload, callback) {
var transportOptions = apiUtility_transportOptions(this.transportOptions, 'POST');
this.transport.postJsonPayload(this.accessToken, transportOptions, jsonPayload, callback);
}
}, {
key: "configure",
value: function configure(options) {
var oldOptions = this.options;
this.options = merge(oldOptions, options);
this.transportOptions = _getTransport(this.options, this.url);
this.OTLPTransportOptions = _getOTLPTransport(this.options, this.url);
if (this.options.accessToken !== undefined) {
this.accessToken = this.options.accessToken;
}
return this;
}
}]);
}();
function _getTransport(options, url) {
return getTransportFromOptions(options, defaultOptions, url);
}
function _getOTLPTransport(options, url) {
var _options$tracing;
options = _objectSpread(_objectSpread({}, options), {}, {
endpoint: (_options$tracing = options.tracing) === null || _options$tracing === void 0 ? void 0 : _options$tracing.endpoint
});
return getTransportFromOptions(options, OTLPDefaultOptions, url);
}
/* harmony default export */ const src_api = (Api);
;// ./src/defaults.js
/**
* Default options shared across platforms
*/
var version = '3.1.0';
var endpoint = 'api.rollbar.com/api/1/item/';
var logLevel = 'debug';
var reportLevel = 'debug';
var uncaughtErrorLevel = 'error';
var maxItems = 0;
var itemsPerMin = 60;
var commonScrubFields = ['pw', 'pass', 'passwd', 'password', 'secret', 'confirm_password', 'confirmPassword', 'password_confirmation', 'passwordConfirmation', 'access_token', 'accessToken', 'X-Rollbar-Access-Token', 'secret_key', 'secretKey', 'secretToken'];
var apiScrubFields = ['api_key', 'authenticity_token', 'oauth_token', 'token', 'user_session_secret'];
var requestScrubFields = ['request.session.csrf', 'request.session._csrf', 'request.params._csrf', 'request.cookie', 'request.cookies'];
var commonScrubHeaders = ['authorization', 'www-authorization', 'http_authorization', 'omniauth.auth', 'cookie', 'oauth-access-token', 'x-access-token', 'x_csrf_token', 'http_x_csrf_token', 'x-csrf-token'];
// For backward compatibility with default export
/* harmony default export */ const defaults = ({
version: version,
endpoint: endpoint,
logLevel: logLevel,
reportLevel: reportLevel,
uncaughtErrorLevel: uncaughtErrorLevel,
maxItems: maxItems,
itemsPerMin: itemsPerMin
});
;// ./src/logger.js
var _log = function log() {};
var levels = {
debug: 0,
info: 1,
warn: 2,
error: 3,
disable: 4
};
var logger = {
error: function error() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _log('error', args);
},
warn: function warn() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _log('warn', args);
},
info: function info() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return _log('info', args);
},
debug: function debug() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return _log('debug', args);
},
log: function log() {
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
return _log('info', args);
},
init: function init(_ref) {
var logLevel = _ref.logLevel;
_log = function _log(level, args) {
if (levels[level] < levels[logLevel]) return;
args.unshift('Rollbar:');
// eslint-disable-next-line no-console
console[level].apply(console, args);
};
}
};
/* harmony default export */ const src_logger = (logger);
;// ./src/predicates.js
function predicates_createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = predicates_unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function predicates_unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return predicates_arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? predicates_arrayLikeToArray(r, a) : void 0; } }
function predicates_arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function checkLevel(item, settings) {
var level = item.level;
var levelVal = LEVELS[level] || 0;
var reportLevel = settings.reportLevel;
var reportLevelVal = LEVELS[reportLevel] || 0;
if (levelVal < reportLevelVal) {
return false;
}
return true;
}
function userCheckIgnore(logger) {
return function (item, settings) {
var isUncaught = Boolean(item._isUncaught);
delete item._isUncaught;
var args = item._originalArgs;
delete item._originalArgs;
try {
if (isFunction(settings.onSendCallback)) {
settings.onSendCallback(isUncaught, args, item);
}
} catch (e) {
settings.onSendCallback = null;
logger.error('Error while calling onSendCallback, removing', e);
}
try {
if (isFunction(settings.checkIgnore) && settings.checkIgnore(isUncaught, args, item)) {
return false;
}
} catch (e) {
settings.checkIgnore = null;
logger.error('Error while calling custom checkIgnore(), removing', e);
}
return true;
};
}
function urlIsNotBlockListed(logger) {
return function (item, settings) {
return !urlIsOnAList(item, settings, 'blocklist', logger);
};
}
function urlIsSafeListed(logger) {
return function (item, settings) {
return urlIsOnAList(item, settings, 'safelist', logger);
};
}
function matchFrames(trace, list, block) {
if (!trace) {
return !block;
}
var frames = trace.frames;
if (!frames || frames.length === 0) {
return !block;
}
var frame, filename, url, urlRegex;
var listLength = list.length;
var frameLength = frames.length;
for (var i = 0; i < frameLength; i++) {
frame = frames[i];
filename = frame.filename;
if (!isType(filename, 'string')) {
return !block;
}
for (var j = 0; j < listLength; j++) {
url = list[j];
urlRegex = new RegExp(url);
if (urlRegex.test(filename)) {
return true;
}
}
}
return false;
}
function urlIsOnAList(item, settings, safeOrBlock, logger) {
// safelist is the default
var block = false;
if (safeOrBlock === 'blocklist') {
block = true;
}
var list, traces;
try {
list = block ? settings.hostBlockList : settings.hostSafeList;
traces = get(item, 'body.trace_chain') || [get(item, 'body.trace')];
// These two checks are important to come first as they are defaults
// in case the list is missing or the trace is missing or not well-formed
if (!list || list.length === 0) {
return !block;
}
if (traces.length === 0 || !traces[0]) {
return !block;
}
var tracesLength = traces.length;
for (var i = 0; i < tracesLength; i++) {
if (matchFrames(traces[i], list, block)) {
return true;
}
}
} catch (e
/* istanbul ignore next */) {
if (block) {
settings.hostBlockList = null;
} else {
settings.hostSafeList = null;
}
var listName = block ? 'hostBlockList' : 'hostSafeList';
logger.error("Error while reading your configuration's " + listName + ' option. Removing custom ' + listName + '.', e);
return !block;
}
return false;
}
function messageIsIgnored(logger) {
return function (item, settings) {
var i, j, ignoredMessages, len, messageIsIgnored, rIgnoredMessage, messages;
try {
messageIsIgnored = false;
ignoredMessages = settings.ignoredMessages;
if (!ignoredMessages || ignoredMessages.length === 0) {
return true;
}
messages = messagesFromItem(item);
if (messages.length === 0) {
return true;
}
len = ignoredMessages.length;
for (i = 0; i < len; i++) {
rIgnoredMessage = new RegExp(ignoredMessages[i], 'gi');
for (j = 0; j < messages.length; j++) {
messageIsIgnored = rIgnoredMessage.test(messages[j]);
if (messageIsIgnored) {
return false;
}
}
}
} catch (_e
/* istanbul ignore next */) {
settings.ignoredMessages = null;
logger.error("Error while reading your configuration's ignoredMessages option. Removing custom ignoredMessages.");
}
return true;
};
}
function messagesFromItem(item) {
var body = item.body;
var messages = [];
// The payload schema only allows one of trace_