g(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}
function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null;
"undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}
function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;
function M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};
exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};
/***/ }),
/***/ 840:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
if (true) {
module.exports = __webpack_require__(53);
} else {}
/***/ }),
/***/ 684:
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* URI.js - Mutating URLs
* IPv6 Support
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
(function (root, factory) {
'use strict';
// https://github.com/umdjs/umd/blob/master/returnExports.js
if ( true && module.exports) {
// Node
module.exports = factory();
} else if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}(this, function (root) {
'use strict';
/*
var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156";
var _out = IPv6.best(_in);
var _expected = "fe80::204:61ff:fe9d:f156";
console.log(_in, _out, _expected, _out === _expected);
*/
// save current IPv6 variable, if any
var _IPv6 = root && root.IPv6;
function bestPresentation(address) {
// based on:
// Javascript to test an IPv6 address for proper format, and to
// present the "best text representation" according to IETF Draft RFC at
// http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04
// 8 Feb 2010 Rich Brown, Dartware, LLC
// Please feel free to use this code as long as you provide a link to
// http://www.intermapper.com
// http://intermapper.com/support/tools/IPV6-Validator.aspx
// http://download.dartware.com/thirdparty/ipv6validator.js
var _address = address.toLowerCase();
var segments = _address.split(':');
var length = segments.length;
var total = 8;
// trim colons (:: or ::a:b:c… or …a:b:c::)
if (segments[0] === '' && segments[1] === '' && segments[2] === '') {
// must have been ::
// remove first two items
segments.shift();
segments.shift();
} else if (segments[0] === '' && segments[1] === '') {
// must have been ::xxxx
// remove the first item
segments.shift();
} else if (segments[length - 1] === '' && segments[length - 2] === '') {
// must have been xxxx::
segments.pop();
}
length = segments.length;
// adjust total segments for IPv4 trailer
if (segments[length - 1].indexOf('.') !== -1) {
// found a "." which means IPv4
total = 7;
}
// fill empty segments them with "0000"
var pos;
for (pos = 0; pos < length; pos++) {
if (segments[pos] === '') {
break;
}
}
if (pos < total) {
segments.splice(pos, 1, '0000');
while (segments.length < total) {
segments.splice(pos, 0, '0000');
}
}
// strip leading zeros
var _segments;
for (var i = 0; i < total; i++) {
_segments = segments[i].split('');
for (var j = 0; j < 3 ; j++) {
if (_segments[0] === '0' && _segments.length > 1) {
_segments.splice(0,1);
} else {
break;
}
}
segments[i] = _segments.join('');
}
// find longest sequence of zeroes and coalesce them into one segment
var best = -1;
var _best = 0;
var _current = 0;
var current = -1;
var inzeroes = false;
// i; already declared
for (i = 0; i < total; i++) {
if (inzeroes) {
if (segments[i] === '0') {
_current += 1;
} else {
inzeroes = false;
if (_current > _best) {
best = current;
_best = _current;
}
}
} else {
if (segments[i] === '0') {
inzeroes = true;
current = i;
_current = 1;
}
}
}
if (_current > _best) {
best = current;
_best = _current;
}
if (_best > 1) {
segments.splice(best, _best, '');
}
length = segments.length;
// assemble remaining segments
var result = '';
if (segments[0] === '') {
result = ':';
}
for (i = 0; i < length; i++) {
result += segments[i];
if (i === length - 1) {
break;
}
result += ':';
}
if (segments[length - 1] === '') {
result += ':';
}
return result;
}
function noConflict() {
/*jshint validthis: true */
if (root.IPv6 === this) {
root.IPv6 = _IPv6;
}
return this;
}
return {
best: bestPresentation,
noConflict: noConflict
};
}));
/***/ }),
/***/ 106:
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* URI.js - Mutating URLs
* Second Level Domain (SLD) Support
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
(function (root, factory) {
'use strict';
// https://github.com/umdjs/umd/blob/master/returnExports.js
if ( true && module.exports) {
// Node
module.exports = factory();
} else if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}(this, function (root) {
'use strict';
// save current SecondLevelDomains variable, if any
var _SecondLevelDomains = root && root.SecondLevelDomains;
var SLD = {
// list of known Second Level Domains
// converted list of SLDs from https://github.com/gavingmiller/second-level-domains
// ----
// publicsuffix.org is more current and actually used by a couple of browsers internally.
// downside is it also contains domains like "dyndns.org" - which is fine for the security
// issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js
// ----
list: {
'ac':' com gov mil net org ',
'ae':' ac co gov mil name net org pro sch ',
'af':' com edu gov net org ',
'al':' com edu gov mil net org ',
'ao':' co ed gv it og pb ',
'ar':' com edu gob gov int mil net org tur ',
'at':' ac co gv or ',
'au':' asn com csiro edu gov id net org ',
'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ',
'bb':' biz co com edu gov info net org store tv ',
'bh':' biz cc com edu gov info net org ',
'bn':' com edu gov net org ',
'bo':' com edu gob gov int mil net org tv ',
'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ',
'bs':' com edu gov net org ',
'bz':' du et om ov rg ',
'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ',
'ck':' biz co edu gen gov info net org ',
'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ',
'co':' com edu gov mil net nom org ',
'cr':' ac c co ed fi go or sa ',
'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ',
'do':' art com edu gob gov mil net org sld web ',
'dz':' art asso com edu gov net org pol ',
'ec':' com edu fin gov info med mil net org pro ',
'eg':' com edu eun gov mil name net org sci ',
'er':' com edu gov ind mil net org rochest w ',
'es':' com edu gob nom org ',
'et':' biz com edu gov info name net org ',
'fj':' ac biz com info mil name net org pro ',
'fk':' ac co gov net nom org ',
'fr':' asso com f gouv nom prd presse tm ',
'gg':' co net org ',
'gh':' com edu gov mil org ',
'gn':' ac com gov net org ',
'gr':' com edu gov mil net org ',
'gt':' com edu gob ind mil net org ',
'gu':' com edu gov net org ',
'hk':' com edu gov idv net org ',
'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ',
'id':' ac co go mil net or sch web ',
'il':' ac co gov idf k12 muni net org ',
'in':' ac co edu ernet firm gen gov i ind mil net nic org res ',
'iq':' com edu gov i mil net org ',
'ir':' ac co dnssec gov i id net org sch ',
'it':' edu gov ',
'je':' co net org ',
'jo':' com edu gov mil name net org sch ',
'jp':' ac ad co ed go gr lg ne or ',
'ke':' ac co go info me mobi ne or sc ',
'kh':' com edu gov mil net org per ',
'ki':' biz com de edu gov info mob net org tel ',
'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ',
'kn':' edu gov net org ',
'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ',
'kw':' com edu gov net org ',
'ky':' com edu gov net org ',
'kz':' com edu gov mil net org ',
'lb':' com edu gov net org ',
'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ',
'lr':' com edu gov net org ',
'lv':' asn com conf edu gov id mil net org ',
'ly':' com edu gov id med net org plc sch ',
'ma':' ac co gov m net org press ',
'mc':' asso tm ',
'me':' ac co edu gov its net org priv ',
'mg':' com edu gov mil nom org prd tm ',
'mk':' com edu gov inf name net org pro ',
'ml':' com edu gov net org presse ',
'mn':' edu gov org ',
'mo':' com edu gov net org ',
'mt':' com edu gov net org ',
'mv':' aero biz com coop edu gov info int mil museum name net org pro ',
'mw':' ac co com coop edu gov int museum net org ',
'mx':' com edu gob net org ',
'my':' com edu gov mil name net org sch ',
'nf':' arts com firm info net other per rec store web ',
'ng':' biz com edu gov mil mobi name net org sch ',
'ni':' ac co com edu gob mil net nom org ',
'np':' com edu gov mil net org ',
'nr':' biz com edu gov info net org ',
'om':' ac biz co com edu gov med mil museum net org pro sch ',
'pe':' com edu gob mil net nom org sld ',
'ph':' com edu gov i mil net ngo org ',
'pk':' biz com edu fam gob gok gon gop gos gov net org web ',
'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ',
'pr':' ac biz com edu est gov info isla name net org pro prof ',
'ps':' com edu gov net org plo sec ',
'pw':' belau co ed go ne or ',
'ro':' arts com firm info nom nt org rec store tm www ',
'rs':' ac co edu gov in org ',
'sb':' com edu gov net org ',
'sc':' com edu gov net org ',
'sh':' co com edu gov net nom org ',
'sl':' com edu gov net org ',
'st':' co com consulado edu embaixada gov mil net org principe saotome store ',
'sv':' com edu gob org red ',
'sz':' ac co org ',
'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ',
'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ',
'tw':' club com ebiz edu game gov idv mil net org ',
'mu':' ac co com gov net or org ',
'mz':' ac co edu gov org ',
'na':' co com ',
'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ',
'pa':' abo ac com edu gob ing med net nom org sld ',
'pt':' com edu gov int net nome org publ ',
'py':' com edu gov mil net org ',
'qa':' com edu gov mil net org ',
're':' asso com nom ',
'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ',
'rw':' ac co com edu gouv gov int mil net ',
'sa':' com edu gov med net org pub sch ',
'sd':' com edu gov info med net org tv ',
'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ',
'sg':' com edu gov idn net org per ',
'sn':' art com edu gouv org perso univ ',
'sy':' com edu gov mil net news org ',
'th':' ac co go in mi net or ',
'tj':' ac biz co com edu go gov info int mil name net nic org test web ',
'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ',
'tz':' ac co go ne or ',
'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ',
'ug':' ac co go ne or org sc ',
'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ',
'us':' dni fed isa kids nsn ',
'uy':' com edu gub mil net org ',
've':' co com edu gob info mil net org web ',
'vi':' co com k12 net org ',
'vn':' ac biz com edu gov health info int name net org pro ',
'ye':' co com gov ltd me net org plc ',
'yu':' ac co edu gov org ',
'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ',
'zm':' ac co com edu gov net org sch ',
// https://en.wikipedia.org/wiki/CentralNic#Second-level_domains
'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ',
'net': 'gb jp se uk ',
'org': 'ae',
'de': 'com '
},
// gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost
// in both performance and memory footprint. No initialization required.
// http://jsperf.com/uri-js-sld-regex-vs-binary-search/4
// Following methods use lastIndexOf() rather than array.split() in order
// to avoid any memory allocations.
has: function(domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
return false;
}
var sldOffset = domain.lastIndexOf('.', tldOffset-1);
if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
return false;
}
var sldList = SLD.list[domain.slice(tldOffset+1)];
if (!sldList) {
return false;
}
return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0;
},
is: function(domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
return false;
}
var sldOffset = domain.lastIndexOf('.', tldOffset-1);
if (sldOffset >= 0) {
return false;
}
var sldList = SLD.list[domain.slice(tldOffset+1)];
if (!sldList) {
return false;
}
return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0;
},
get: function(domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
return null;
}
var sldOffset = domain.lastIndexOf('.', tldOffset-1);
if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
return null;
}
var sldList = SLD.list[domain.slice(tldOffset+1)];
if (!sldList) {
return null;
}
if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) {
return null;
}
return domain.slice(sldOffset+1);
},
noConflict: function(){
if (root.SecondLevelDomains === this) {
root.SecondLevelDomains = _SecondLevelDomains;
}
return this;
}
};
return SLD;
}));
/***/ }),
/***/ 998:
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* URI.js - Mutating URLs
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
(function (root, factory) {
'use strict';
// https://github.com/umdjs/umd/blob/master/returnExports.js
if ( true && module.exports) {
// Node
module.exports = factory(__webpack_require__(132), __webpack_require__(684), __webpack_require__(106));
} else if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(132), __webpack_require__(684), __webpack_require__(106)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}(this, function (punycode, IPv6, SLD, root) {
'use strict';
/*global location, escape, unescape */
// FIXME: v2.0.0 renamce non-camelCase properties to uppercase
/*jshint camelcase: false */
// save current URI variable, if any
var _URI = root && root.URI;
function URI(url, base) {
var _urlSupplied = arguments.length >= 1;
var _baseSupplied = arguments.length >= 2;
// Allow instantiation without the 'new' keyword
if (!(this instanceof URI)) {
if (_urlSupplied) {
if (_baseSupplied) {
return new URI(url, base);
}
return new URI(url);
}
return new URI();
}
if (url === undefined) {
if (_urlSupplied) {
throw new TypeError('undefined is not a valid argument for URI');
}
if (typeof location !== 'undefined') {
url = location.href + '';
} else {
url = '';
}
}
if (url === null) {
if (_urlSupplied) {
throw new TypeError('null is not a valid argument for URI');
}
}
this.href(url);
// resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor
if (base !== undefined) {
return this.absoluteTo(base);
}
return this;
}
function isInteger(value) {
return /^[0-9]+$/.test(value);
}
URI.version = '1.19.11';
var p = URI.prototype;
var hasOwn = Object.prototype.hasOwnProperty;
function escapeRegEx(string) {
// https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963
return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
function getType(value) {
// IE8 doesn't return [Object Undefined] but [Object Object] for undefined value
if (value === undefined) {
return 'Undefined';
}
return String(Object.prototype.toString.call(value)).slice(8, -1);
}
function isArray(obj) {
return getType(obj) === 'Array';
}
function filterArrayValues(data, value) {
var lookup = {};
var i, length;
if (getType(value) === 'RegExp') {
lookup = null;
} else if (isArray(value)) {
for (i = 0, length = value.length; i < length; i++) {
lookup[value[i]] = true;
}
} else {
lookup[value] = true;
}
for (i = 0, length = data.length; i < length; i++) {
/*jshint laxbreak: true */
var _match = lookup && lookup[data[i]] !== undefined
|| !lookup && value.test(data[i]);
/*jshint laxbreak: false */
if (_match) {
data.splice(i, 1);
length--;
i--;
}
}
return data;
}
function arrayContains(list, value) {
var i, length;
// value may be string, number, array, regexp
if (isArray(value)) {
// Note: this can be optimized to O(n) (instead of current O(m * n))
for (i = 0, length = value.length; i < length; i++) {
if (!arrayContains(list, value[i])) {
return false;
}
}
return true;
}
var _type = getType(value);
for (i = 0, length = list.length; i < length; i++) {
if (_type === 'RegExp') {
if (typeof list[i] === 'string' && list[i].match(value)) {
return true;
}
} else if (list[i] === value) {
return true;
}
}
return false;
}
function arraysEqual(one, two) {
if (!isArray(one) || !isArray(two)) {
return false;
}
// arrays can't be equal if they have different amount of content
if (one.length !== two.length) {
return false;
}
one.sort();
two.sort();
for (var i = 0, l = one.length; i < l; i++) {
if (one[i] !== two[i]) {
return false;
}
}
return true;
}
function trimSlashes(text) {
var trim_expression = /^\/+|\/+$/g;
return text.replace(trim_expression, '');
}
URI._parts = function() {
return {
protocol: null,
username: null,
password: null,
hostname: null,
urn: null,
port: null,
path: null,
query: null,
fragment: null,
// state
preventInvalidHostname: URI.preventInvalidHostname,
duplicateQueryParameters: URI.duplicateQueryParameters,
escapeQuerySpace: URI.escapeQuerySpace
};
};
// state: throw on invalid hostname
// see https://github.com/medialize/URI.js/pull/345
// and https://github.com/medialize/URI.js/issues/354
URI.preventInvalidHostname = false;
// state: allow duplicate query parameters (a=1&a=1)
URI.duplicateQueryParameters = false;
// state: replaces + with %20 (space in query strings)
URI.escapeQuerySpace = true;
// static properties
URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i;
URI.idn_expression = /[^a-z0-9\._-]/i;
URI.punycode_expression = /(xn--)/i;
// well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care?
URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
// credits to Rich Brown
// source: http://forums.intermapper.com/viewtopic.php?p=1096#1096
// specification: http://www.ietf.org/rfc/rfc4291.txt
URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
// expression used is "gruber revised" (@gruber v2) determined to be the
// best solution in a regex-golf we did a couple of ages ago at
// * http://mathiasbynens.be/demo/url-regex
// * http://rodneyrehm.de/t/url-regex.html
URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig;
URI.findUri = {
// valid "scheme://" or "www."
start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,
// everything up to the next whitespace
end: /[\s\r\n]|$/,
// trim trailing punctuation captured by end RegExp
trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/,
// balanced parens inclusion (), [], {}, <>
parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g,
};
URI.leading_whitespace_expression = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
URI.ascii_tab_whitespace = /[\u0009\u000A\u000D]+/g
// http://www.iana.org/assignments/uri-schemes.html
// http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports
URI.defaultPorts = {
http: '80',
https: '443',
ftp: '21',
gopher: '70',
ws: '80',
wss: '443'
};
// list of protocols which always require a hostname
URI.hostProtocols = [
'http',
'https'
];
// allowed hostname characters according to RFC 3986
// ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded
// I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _
URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/;
// map DOM Elements to their URI attribute
URI.domAttributes = {
'a': 'href',
'blockquote': 'cite',
'link': 'href',
'base': 'href',
'script': 'src',
'form': 'action',
'img': 'src',
'area': 'href',
'iframe': 'src',
'embed': 'src',
'source': 'src',
'track': 'src',
'input': 'src', // but only if type="image"
'audio': 'src',
'video': 'src'
};
URI.getDomAttribute = function(node) {
if (!node || !node.nodeName) {
return undefined;
}
var nodeName = node.nodeName.toLowerCase();
// should only expose src for type="image"
if (nodeName === 'input' && node.type !== 'image') {
return undefined;
}
return URI.domAttributes[nodeName];
};
function escapeForDumbFirefox36(value) {
// https://github.com/medialize/URI.js/issues/91
return escape(value);
}
// encoding / decoding according to RFC3986
function strictEncodeURIComponent(string) {
// see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
return encodeURIComponent(string)
.replace(/[!'()*]/g, escapeForDumbFirefox36)
.replace(/\*/g, '%2A');
}
URI.encode = strictEncodeURIComponent;
URI.decode = decodeURIComponent;
URI.iso8859 = function() {
URI.encode = escape;
URI.decode = unescape;
};
URI.unicode = function() {
URI.encode = strictEncodeURIComponent;
URI.decode = decodeURIComponent;
};
URI.characters = {
pathname: {
encode: {
// RFC3986 2.1: For consistency, URI producers and normalizers should
// use uppercase hexadecimal digits for all percent-encodings.
expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig,
map: {
// -._~!'()*
'%24': '$',
'%26': '&',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '=',
'%3A': ':',
'%40': '@'
}
},
decode: {
expression: /[\/\?#]/g,
map: {
'/': '%2F',
'?': '%3F',
'#': '%23'
}
}
},
reserved: {
encode: {
// RFC3986 2.1: For consistency, URI producers and normalizers should
// use uppercase hexadecimal digits for all percent-encodings.
expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,
map: {
// gen-delims
'%3A': ':',
'%2F': '/',
'%3F': '?',
'%23': '#',
'%5B': '[',
'%5D': ']',
'%40': '@',
// sub-delims
'%21': '!',
'%24': '$',
'%26': '&',
'%27': '\'',
'%28': '(',
'%29': ')',
'%2A': '*',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '='
}
}
},
urnpath: {
// The characters under `encode` are the characters called out by RFC 2141 as being acceptable
// for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but
// these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also
// note that the colon character is not featured in the encoding map; this is because URI.js
// gives the colons in URNs semantic meaning as the delimiters of path segements, and so it
// should not appear unencoded in a segment itself.
// See also the note above about RFC3986 and capitalalized hex digits.
encode: {
expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,
map: {
'%21': '!',
'%24': '$',
'%27': '\'',
'%28': '(',
'%29': ')',
'%2A': '*',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '=',
'%40': '@'
}
},
// These characters are the characters called out by RFC2141 as "reserved" characters that
// should never appear in a URN, plus the colon character (see note above).
decode: {
expression: /[\/\?#:]/g,
map: {
'/': '%2F',
'?': '%3F',
'#': '%23',
':': '%3A'
}
}
}
};
URI.encodeQuery = function(string, escapeQuerySpace) {
var escaped = URI.encode(string + '');
if (escapeQuerySpace === undefined) {
escapeQuerySpace = URI.escapeQuerySpace;
}
return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped;
};
URI.decodeQuery = function(string, escapeQuerySpace) {
string += '';
if (escapeQuerySpace === undefined) {
escapeQuerySpace = URI.escapeQuerySpace;
}
try {
return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string);
} catch(e) {
// we're not going to mess with weird encodings,
// give up and return the undecoded original string
// see https://github.com/medialize/URI.js/issues/87
// see https://github.com/medialize/URI.js/issues/92
return string;
}
};
// generate encode/decode path functions
var _parts = {'encode':'encode', 'decode':'decode'};
var _part;
var generateAccessor = function(_group, _part) {
return function(string) {
try {
return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) {
return URI.characters[_group][_part].map[c];
});
} catch (e) {
// we're not going to mess with weird encodings,
// give up and return the undecoded original string
// see https://github.com/medialize/URI.js/issues/87
// see https://github.com/medialize/URI.js/issues/92
return string;
}
};
};
for (_part in _parts) {
URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]);
URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]);
}
var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) {
return function(string) {
// Why pass in names of functions, rather than the function objects themselves? The
// definitions of some functions (but in particular, URI.decode) will occasionally change due
// to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure
// that the functions we use here are "fresh".
var actualCodingFunc;
if (!_innerCodingFuncName) {
actualCodingFunc = URI[_codingFuncName];
} else {
actualCodingFunc = function(string) {
return URI[_codingFuncName](URI[_innerCodingFuncName](string));
};
}
var segments = (string + '').split(_sep);
for (var i = 0, length = segments.length; i < length; i++) {
segments[i] = actualCodingFunc(segments[i]);
}
return segments.join(_sep);
};
};
// This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions.
URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment');
URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment');
URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');
URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');
URI.encodeReserved = generateAccessor('reserved', 'encode');
URI.parse = function(string, parts) {
var pos;
if (!parts) {
parts = {
preventInvalidHostname: URI.preventInvalidHostname
};
}
string = string.replace(URI.leading_whitespace_expression, '')
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
string = string.replace(URI.ascii_tab_whitespace, '')
// [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment]
// extract fragment
pos = string.indexOf('#');
if (pos > -1) {
// escaping?
parts.fragment = string.substring(pos + 1) || null;
string = string.substring(0, pos);
}
// extract query
pos = string.indexOf('?');
if (pos > -1) {
// escaping?
parts.query = string.substring(pos + 1) || null;
string = string.substring(0, pos);
}
// slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws)
string = string.replace(/^(https?|ftp|wss?)?:+[/\\]*/i, '$1://');
// slashes and backslashes have lost all meaning for scheme relative URLs
string = string.replace(/^[/\\]{2,}/i, '//');
// extract protocol
if (string.substring(0, 2) === '//') {
// relative-scheme
parts.protocol = null;
string = string.substring(2);
// extract "user:pass@host:port"
string = URI.parseAuthority(string, parts);
} else {
pos = string.indexOf(':');
if (pos > -1) {
parts.protocol = string.substring(0, pos) || null;
if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {
// : may be within the path
parts.protocol = undefined;
} else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') {
string = string.substring(pos + 3);
// extract "user:pass@host:port"
string = URI.parseAuthority(string, parts);
} else {
string = string.substring(pos + 1);
parts.urn = true;
}
}
}
// what's left must be the path
parts.path = string;
// and we're done
return parts;
};
URI.parseHost = function(string, parts) {
if (!string) {
string = '';
}
// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124
// See: https://code.google.com/p/chromium/issues/detail?id=25916
// https://github.com/medialize/URI.js/pull/233
string = string.replace(/\\/g, '/');
// extract host:port
var pos = string.indexOf('/');
var bracketPos;
var t;
if (pos === -1) {
pos = string.length;
}
if (string.charAt(0) === '[') {
// IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6
// I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts
// IPv6+port in the format [2001:db8::1]:80 (for the time being)
bracketPos = string.indexOf(']');
parts.hostname = string.substring(1, bracketPos) || null;
parts.port = string.substring(bracketPos + 2, pos) || null;
if (parts.port === '/') {
parts.port = null;
}
} else {
var firstColon = string.indexOf(':');
var firstSlash = string.indexOf('/');
var nextColon = string.indexOf(':', firstColon + 1);
if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) {
// IPv6 host contains multiple colons - but no port
// this notation is actually not allowed by RFC 3986, but we're a liberal parser
parts.hostname = string.substring(0, pos) || null;
parts.port = null;
} else {
t = string.substring(0, pos).split(':');
parts.hostname = t[0] || null;
parts.port = t[1] || null;
}
}
if (parts.hostname && string.substring(pos).charAt(0) !== '/') {
pos++;
string = '/' + string;
}
if (parts.preventInvalidHostname) {
URI.ensureValidHostname(parts.hostname, parts.protocol);
}
if (parts.port) {
URI.ensureValidPort(parts.port);
}
return string.substring(pos) || '/';
};
URI.parseAuthority = function(string, parts) {
string = URI.parseUserinfo(string, parts);
return URI.parseHost(string, parts);
};
URI.parseUserinfo = function(string, parts) {
// extract username:password
var _string = string
var firstBackSlash = string.indexOf('\\');
if (firstBackSlash !== -1) {
string = string.replace(/\\/g, '/')
}
var firstSlash = string.indexOf('/');
var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1);
var t;
// authority@ must come before /path or \path
if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) {
t = string.substring(0, pos).split(':');
parts.username = t[0] ? URI.decode(t[0]) : null;
t.shift();
parts.password = t[0] ? URI.decode(t.join(':')) : null;
string = _string.substring(pos + 1);
} else {
parts.username = null;
parts.password = null;
}
return string;
};
URI.parseQuery = function(string, escapeQuerySpace) {
if (!string) {
return {};
}
// throw out the funky business - "?"[name"="value"&"]+
string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, '');
if (!string) {
return {};
}
var items = {};
var splits = string.split('&');
var length = splits.length;
var v, name, value;
for (var i = 0; i < length; i++) {
v = splits[i].split('=');
name = URI.decodeQuery(v.shift(), escapeQuerySpace);
// no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters
value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null;
if (name === '__proto__') {
// ignore attempt at exploiting JavaScript internals
continue;
} else if (hasOwn.call(items, name)) {
if (typeof items[name] === 'string' || items[name] === null) {
items[name] = [items[name]];
}
items[name].push(value);
} else {
items[name] = value;
}
}
return items;
};
URI.build = function(parts) {
var t = '';
var requireAbsolutePath = false
if (parts.protocol) {
t += parts.protocol + ':';
}
if (!parts.urn && (t || parts.hostname)) {
t += '//';
requireAbsolutePath = true
}
t += (URI.buildAuthority(parts) || '');
if (typeof parts.path === 'string') {
if (parts.path.charAt(0) !== '/' && requireAbsolutePath) {
t += '/';
}
t += parts.path;
}
if (typeof parts.query === 'string' && parts.query) {
t += '?' + parts.query;
}
if (typeof parts.fragment === 'string' && parts.fragment) {
t += '#' + parts.fragment;
}
return t;
};
URI.buildHost = function(parts) {
var t = '';
if (!parts.hostname) {
return '';
} else if (URI.ip6_expression.test(parts.hostname)) {
t += '[' + parts.hostname + ']';
} else {
t += parts.hostname;
}
if (parts.port) {
t += ':' + parts.port;
}
return t;
};
URI.buildAuthority = function(parts) {
return URI.buildUserinfo(parts) + URI.buildHost(parts);
};
URI.buildUserinfo = function(parts) {
var t = '';
if (parts.username) {
t += URI.encode(parts.username);
}
if (parts.password) {
t += ':' + URI.encode(parts.password);
}
if (t) {
t += '@';
}
return t;
};
URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) {
// according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html
// being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed
// the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax!
// URI.js treats the query string as being application/x-www-form-urlencoded
// see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type
var t = '';
var unique, key, i, length;
for (key in data) {
if (key === '__proto__') {
// ignore attempt at exploiting JavaScript internals
continue;
} else if (hasOwn.call(data, key)) {
if (isArray(data[key])) {
unique = {};
for (i = 0, length = data[key].length; i < length; i++) {
if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) {
t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace);
if (duplicateQueryParameters !== true) {
unique[data[key][i] + ''] = true;
}
}
}
} else if (data[key] !== undefined) {
t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace);
}
}
}
return t.substring(1);
};
URI.buildQueryParameter = function(name, value, escapeQuerySpace) {
// http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded
// don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization
return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : '');
};
URI.addQuery = function(data, name, value) {
if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
URI.addQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
if (data[name] === undefined) {
data[name] = value;
return;
} else if (typeof data[name] === 'string') {
data[name] = [data[name]];
}
if (!isArray(value)) {
value = [value];
}
data[name] = (data[name] || []).concat(value);
} else {
throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
}
};
URI.setQuery = function(data, name, value) {
if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
URI.setQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
data[name] = value === undefined ? null : value;
} else {
throw new TypeError('URI.setQuery() accepts an object, string as the name parameter');
}
};
URI.removeQuery = function(data, name, value) {
var i, length, key;
if (isArray(name)) {
for (i = 0, length = name.length; i < length; i++) {
data[name[i]] = undefined;
}
} else if (getType(name) === 'RegExp') {
for (key in data) {
if (name.test(key)) {
data[key] = undefined;
}
}
} else if (typeof name === 'object') {
for (key in name) {
if (hasOwn.call(name, key)) {
URI.removeQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
if (value !== undefined) {
if (getType(value) === 'RegExp') {
if (!isArray(data[name]) && value.test(data[name])) {
data[name] = undefined;
} else {
data[name] = filterArrayValues(data[name], value);
}
} else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) {
data[name] = undefined;
} else if (isArray(data[name])) {
data[name] = filterArrayValues(data[name], value);
}
} else {
data[name] = undefined;
}
} else {
throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter');
}
};
URI.hasQuery = function(data, name, value, withinArray) {
switch (getType(name)) {
case 'String':
// Nothing to do here
break;
case 'RegExp':
for (var key in data) {
if (hasOwn.call(data, key)) {
if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) {
return true;
}
}
}
return false;
case 'Object':
for (var _key in name) {
if (hasOwn.call(name, _key)) {
if (!URI.hasQuery(data, _key, name[_key])) {
return false;
}
}
}
return true;
default:
throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter');
}
switch (getType(value)) {
case 'Undefined':
// true if exists (but may be empty)
return name in data; // data[name] !== undefined;
case 'Boolean':
// true if exists and non-empty
var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]);
return value === _booly;
case 'Function':
// allow complex comparison
return !!value(data[name], name, data);
case 'Array':
if (!isArray(data[name])) {
return false;
}
var op = withinArray ? arrayContains : arraysEqual;
return op(data[name], value);
case 'RegExp':
if (!isArray(data[name])) {
return Boolean(data[name] && data[name].match(value));
}
if (!withinArray) {
return false;
}
return arrayContains(data[name], value);
case 'Number':
value = String(value);
/* falls through */
case 'String':
if (!isArray(data[name])) {
return data[name] === value;
}
if (!withinArray) {
return false;
}
return arrayContains(data[name], value);
default:
throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter');
}
};
URI.joinPaths = function() {
var input = [];
var segments = [];
var nonEmptySegments = 0;
for (var i = 0; i < arguments.length; i++) {
var url = new URI(arguments[i]);
input.push(url);
var _segments = url.segment();
for (var s = 0; s < _segments.length; s++) {
if (typeof _segments[s] === 'string') {
segments.push(_segments[s]);
}
if (_segments[s]) {
nonEmptySegments++;
}
}
}
if (!segments.length || !nonEmptySegments) {
return new URI('');
}
var uri = new URI('').segment(segments);
if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') {
uri.path('/' + uri.path());
}
return uri.normalize();
};
URI.commonPath = function(one, two) {
var length = Math.min(one.length, two.length);
var pos;
// find first non-matching character
for (pos = 0; pos < length; pos++) {
if (one.charAt(pos) !== two.charAt(pos)) {
pos--;
break;
}
}
if (pos < 1) {
return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : '';
}
// revert to last /
if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') {
pos = one.substring(0, pos).lastIndexOf('/');
}
return one.substring(0, pos + 1);
};
URI.withinString = function(string, callback, options) {
options || (options = {});
var _start = options.start || URI.findUri.start;
var _end = options.end || URI.findUri.end;
var _trim = options.trim || URI.findUri.trim;
var _parens = options.parens || URI.findUri.parens;
var _attributeOpen = /[a-z0-9-]=["']?$/i;
_start.lastIndex = 0;
while (true) {
var match = _start.exec(string);
if (!match) {
break;
}
var start = match.index;
if (options.ignoreHtml) {
// attribut(e=["']?$)
var attributeOpen = string.slice(Math.max(start - 3, 0), start);
if (attributeOpen && _attributeOpen.test(attributeOpen)) {
continue;
}
}
var end = start + string.slice(start).search(_end);
var slice = string.slice(start, end);
// make sure we include well balanced parens
var parensEnd = -1;
while (true) {
var parensMatch = _parens.exec(slice);
if (!parensMatch) {
break;
}
var parensMatchEnd = parensMatch.index + parensMatch[0].length;
parensEnd = Math.max(parensEnd, parensMatchEnd);
}
if (parensEnd > -1) {
slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, '');
} else {
slice = slice.replace(_trim, '');
}
if (slice.length <= match[0].length) {
// the extract only contains the starting marker of a URI,
// e.g. "www" or "http://"
continue;
}
if (options.ignore && options.ignore.test(slice)) {
continue;
}
end = start + slice.length;
var result = callback(slice, start, end, string);
if (result === undefined) {
_start.lastIndex = end;
continue;
}
result = String(result);
string = string.slice(0, start) + result + string.slice(end);
_start.lastIndex = start + result.length;
}
_start.lastIndex = 0;
return string;
};
URI.ensureValidHostname = function(v, protocol) {
// Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986)
// they are not part of DNS and therefore ignored by URI.js
var hasHostname = !!v; // not null and not an empty string
var hasProtocol = !!protocol;
var rejectEmptyHostname = false;
if (hasProtocol) {
rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol);
}
if (rejectEmptyHostname && !hasHostname) {
throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol);
} else if (v && v.match(URI.invalid_hostname_characters)) {
// test punycode
if (!punycode) {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');
}
if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]');
}
}
};
URI.ensureValidPort = function (v) {
if (!v) {
return;
}
var port = Number(v);
if (isInteger(port) && (port > 0) && (port < 65536)) {
return;
}
throw new TypeError('Port "' + v + '" is not a valid port');
};
// noConflict
URI.noConflict = function(removeAll) {
if (removeAll) {
var unconflicted = {
URI: this.noConflict()
};
if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') {
unconflicted.URITemplate = root.URITemplate.noConflict();
}
if (root.IPv6 && typeof root.IPv6.noConflict === 'function') {
unconflicted.IPv6 = root.IPv6.noConflict();
}
if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') {
unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict();
}
return unconflicted;
} else if (root.URI === this) {
root.URI = _URI;
}
return this;
};
p.build = function(deferBuild) {
if (deferBuild === true) {
this._deferred_build = true;
} else if (deferBuild === undefined || this._deferred_build) {
this._string = URI.build(this._parts);
this._deferred_build = false;
}
return this;
};
p.clone = function() {
return new URI(this);
};
p.valueOf = p.toString = function() {
return this.build(false)._string;
};
function generateSimpleAccessor(_part){
return function(v, build) {
if (v === undefined) {
return this._parts[_part] || '';
} else {
this._parts[_part] = v || null;
this.build(!build);
return this;
}
};
}
function generatePrefixAccessor(_part, _key){
return function(v, build) {
if (v === undefined) {
return this._parts[_part] || '';
} else {
if (v !== null) {
v = v + '';
if (v.charAt(0) === _key) {
v = v.substring(1);
}
}
this._parts[_part] = v;
this.build(!build);
return this;
}
};
}
p.protocol = generateSimpleAccessor('protocol');
p.username = generateSimpleAccessor('username');
p.password = generateSimpleAccessor('password');
p.hostname = generateSimpleAccessor('hostname');
p.port = generateSimpleAccessor('port');
p.query = generatePrefixAccessor('query', '?');
p.fragment = generatePrefixAccessor('fragment', '#');
p.search = function(v, build) {
var t = this.query(v, build);
return typeof t === 'string' && t.length ? ('?' + t) : t;
};
p.hash = function(v, build) {
var t = this.fragment(v, build);
return typeof t === 'string' && t.length ? ('#' + t) : t;
};
p.pathname = function(v, build) {
if (v === undefined || v === true) {
var res = this._parts.path || (this._parts.hostname ? '/' : '');
return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res;
} else {
if (this._parts.urn) {
this._parts.path = v ? URI.recodeUrnPath(v) : '';
} else {
this._parts.path = v ? URI.recodePath(v) : '/';
}
this.build(!build);
return this;
}
};
p.path = p.pathname;
p.href = function(href, build) {
var key;
if (href === undefined) {
return this.toString();
}
this._string = '';
this._parts = URI._parts();
var _URI = href instanceof URI;
var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname);
if (href.nodeName) {
var attribute = URI.getDomAttribute(href);
href = href[attribute] || '';
_object = false;
}
// window.location is reported to be an object, but it's not the sort
// of object we're looking for:
// * location.protocol ends with a colon
// * location.query != object.search
// * location.hash != object.fragment
// simply serializing the unknown object should do the trick
// (for location, not for everything...)
if (!_URI && _object && href.pathname !== undefined) {
href = href.toString();
}
if (typeof href === 'string' || href instanceof String) {
this._parts = URI.parse(String(href), this._parts);
} else if (_URI || _object) {
var src = _URI ? href._parts : href;
for (key in src) {
if (key === 'query') { continue; }
if (hasOwn.call(this._parts, key)) {
this._parts[key] = src[key];
}
}
if (src.query) {
this.query(src.query, false);
}
} else {
throw new TypeError('invalid input');
}
this.build(!build);
return this;
};
// identification accessors
p.is = function(what) {
var ip = false;
var ip4 = false;
var ip6 = false;
var name = false;
var sld = false;
var idn = false;
var punycode = false;
var relative = !this._parts.urn;
if (this._parts.hostname) {
relative = false;
ip4 = URI.ip4_expression.test(this._parts.hostname);
ip6 = URI.ip6_expression.test(this._parts.hostname);
ip = ip4 || ip6;
name = !ip;
sld = name && SLD && SLD.has(this._parts.hostname);
idn = name && URI.idn_expression.test(this._parts.hostname);
punycode = name && URI.punycode_expression.test(this._parts.hostname);
}
switch (what.toLowerCase()) {
case 'relative':
return relative;
case 'absolute':
return !relative;
// hostname identification
case 'domain':
case 'name':
return name;
case 'sld':
return sld;
case 'ip':
return ip;
case 'ip4':
case 'ipv4':
case 'inet4':
return ip4;
case 'ip6':
case 'ipv6':
case 'inet6':
return ip6;
case 'idn':
return idn;
case 'url':
return !this._parts.urn;
case 'urn':
return !!this._parts.urn;
case 'punycode':
return punycode;
}
return null;
};
// component specific input validation
var _protocol = p.protocol;
var _port = p.port;
var _hostname = p.hostname;
p.protocol = function(v, build) {
if (v) {
// accept trailing ://
v = v.replace(/:(\/\/)?$/, '');
if (!v.match(URI.protocol_expression)) {
throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]');
}
}
return _protocol.call(this, v, build);
};
p.scheme = p.protocol;
p.port = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v !== undefined) {
if (v === 0) {
v = null;
}
if (v) {
v += '';
if (v.charAt(0) === ':') {
v = v.substring(1);
}
URI.ensureValidPort(v);
}
}
return _port.call(this, v, build);
};
p.hostname = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v !== undefined) {
var x = { preventInvalidHostname: this._parts.preventInvalidHostname };
var res = URI.parseHost(v, x);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
v = x.hostname;
if (this._parts.preventInvalidHostname) {
URI.ensureValidHostname(v, this._parts.protocol);
}
}
return _hostname.call(this, v, build);
};
// compound accessors
p.origin = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
var protocol = this.protocol();
var authority = this.authority();
if (!authority) {
return '';
}
return (protocol ? protocol + '://' : '') + this.authority();
} else {
var origin = URI(v);
this
.protocol(origin.protocol())
.authority(origin.authority())
.build(!build);
return this;
}
};
p.host = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
return this._parts.hostname ? URI.buildHost(this._parts) : '';
} else {
var res = URI.parseHost(v, this._parts);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
this.build(!build);
return this;
}
};
p.authority = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
return this._parts.hostname ? URI.buildAuthority(this._parts) : '';
} else {
var res = URI.parseAuthority(v, this._parts);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
this.build(!build);
return this;
}
};
p.userinfo = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
var t = URI.buildUserinfo(this._parts);
return t ? t.substring(0, t.length -1) : t;
} else {
if (v[v.length-1] !== '@') {
v += '@';
}
URI.parseUserinfo(v, this._parts);
this.build(!build);
return this;
}
};
p.resource = function(v, build) {
var parts;
if (v === undefined) {
return this.path() + this.search() + this.hash();
}
parts = URI.parse(v);
this._parts.path = parts.path;
this._parts.query = parts.query;
this._parts.fragment = parts.fragment;
this.build(!build);
return this;
};
// fraction accessors
p.subdomain = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
// convenience, return "www" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
// grab domain and add another segment
var end = this._parts.hostname.length - this.domain().length - 1;
return this._parts.hostname.substring(0, end) || '';
} else {
var e = this._parts.hostname.length - this.domain().length;
var sub = this._parts.hostname.substring(0, e);
var replace = new RegExp('^' + escapeRegEx(sub));
if (v && v.charAt(v.length - 1) !== '.') {
v += '.';
}
if (v.indexOf(':') !== -1) {
throw new TypeError('Domains cannot contain colons');
}
if (v) {
URI.ensureValidHostname(v, this._parts.protocol);
}
this._parts.hostname = this._parts.hostname.replace(replace, v);
this.build(!build);
return this;
}
};
p.domain = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v === 'boolean') {
build = v;
v = undefined;
}
// convenience, return "example.org" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
// if hostname consists of 1 or 2 segments, it must be the domain
var t = this._parts.hostname.match(/\./g);
if (t && t.length < 2) {
return this._parts.hostname;
}
// grab tld and add another segment
var end = this._parts.hostname.length - this.tld(build).length - 1;
end = this._parts.hostname.lastIndexOf('.', end -1) + 1;
return this._parts.hostname.substring(end) || '';
} else {
if (!v) {
throw new TypeError('cannot set domain empty');
}
if (v.indexOf(':') !== -1) {
throw new TypeError('Domains cannot contain colons');
}
URI.ensureValidHostname(v, this._parts.protocol);
if (!this._parts.hostname || this.is('IP')) {
this._parts.hostname = v;
} else {
var replace = new RegExp(escapeRegEx(this.domain()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.tld = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v === 'boolean') {
build = v;
v = undefined;
}
// return "org" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
var pos = this._parts.hostname.lastIndexOf('.');
var tld = this._parts.hostname.substring(pos + 1);
if (build !== true && SLD && SLD.list[tld.toLowerCase()]) {
return SLD.get(this._parts.hostname) || tld;
}
return tld;
} else {
var replace;
if (!v) {
throw new TypeError('cannot set TLD empty');
} else if (v.match(/[^a-zA-Z0-9-]/)) {
if (SLD && SLD.is(v)) {
replace = new RegExp(escapeRegEx(this.tld()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
} else {
throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]');
}
} else if (!this._parts.hostname || this.is('IP')) {
throw new ReferenceError('cannot set TLD on non-domain host');
} else {
replace = new RegExp(escapeRegEx(this.tld()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.directory = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined || v === true) {
if (!this._parts.path && !this._parts.hostname) {
return '';
}
if (this._parts.path === '/') {
return '/';
}
var end = this._parts.path.length - this.filename().length - 1;
var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : '');
return v ? URI.decodePath(res) : res;
} else {
var e = this._parts.path.length - this.filename().length;
var directory = this._parts.path.substring(0, e);
var replace = new RegExp('^' + escapeRegEx(directory));
// fully qualifier directories begin with a slash
if (!this.is('relative')) {
if (!v) {
v = '/';
}
if (v.charAt(0) !== '/') {
v = '/' + v;
}
}
// directories always end with a slash
if (v && v.charAt(v.length - 1) !== '/') {
v += '/';
}
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
this.build(!build);
return this;
}
};
p.filename = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v !== 'string') {
if (!this._parts.path || this._parts.path === '/') {
return '';
}
var pos = this._parts.path.lastIndexOf('/');
var res = this._parts.path.substring(pos+1);
return v ? URI.decodePathSegment(res) : res;
} else {
var mutatedDirectory = false;
if (v.charAt(0) === '/') {
v = v.substring(1);
}
if (v.match(/\.?\//)) {
mutatedDirectory = true;
}
var replace = new RegExp(escapeRegEx(this.filename()) + '$');
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
if (mutatedDirectory) {
this.normalizePath(build);
} else {
this.build(!build);
}
return this;
}
};
p.suffix = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined || v === true) {
if (!this._parts.path || this._parts.path === '/') {
return '';
}
var filename = this.filename();
var pos = filename.lastIndexOf('.');
var s, res;
if (pos === -1) {
return '';
}
// suffix may only contain alnum characters (yup, I made this up.)
s = filename.substring(pos+1);
res = (/^[a-z0-9%]+$/i).test(s) ? s : '';
return v ? URI.decodePathSegment(res) : res;
} else {
if (v.charAt(0) === '.') {
v = v.substring(1);
}
var suffix = this.suffix();
var replace;
if (!suffix) {
if (!v) {
return this;
}
this._parts.path += '.' + URI.recodePath(v);
} else if (!v) {
replace = new RegExp(escapeRegEx('.' + suffix) + '$');
} else {
replace = new RegExp(escapeRegEx(suffix) + '$');
}
if (replace) {
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.segment = function(segment, v, build) {
var separator = this._parts.urn ? ':' : '/';
var path = this.path();
var absolute = path.substring(0, 1) === '/';
var segments = path.split(separator);
if (segment !== undefined && typeof segment !== 'number') {
build = v;
v = segment;
segment = undefined;
}
if (segment !== undefined && typeof segment !== 'number') {
throw new Error('Bad segment "' + segment + '", must be 0-based integer');
}
if (absolute) {
segments.shift();
}
if (segment < 0) {
// allow negative indexes to address from the end
segment = Math.max(segments.length + segment, 0);
}
if (v === undefined) {
/*jshint laxbreak: true */
return segment === undefined
? segments
: segments[segment];
/*jshint laxbreak: false */
} else if (segment === null || segments[segment] === undefined) {
if (isArray(v)) {
segments = [];
// collapse empty elements within array
for (var i=0, l=v.length; i < l; i++) {
if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) {
continue;
}
if (segments.length && !segments[segments.length -1].length) {
segments.pop();
}
segments.push(trimSlashes(v[i]));
}
} else if (v || typeof v === 'string') {
v = trimSlashes(v);
if (segments[segments.length -1] === '') {
// empty trailing elements have to be overwritten
// to prevent results such as /foo//bar
segments[segments.length -1] = v;
} else {
segments.push(v);
}
}
} else {
if (v) {
segments[segment] = trimSlashes(v);
} else {
segments.splice(segment, 1);
}
}
if (absolute) {
segments.unshift('');
}
return this.path(segments.join(separator), build);
};
p.segmentCoded = function(segment, v, build) {
var segments, i, l;
if (typeof segment !== 'number') {
build = v;
v = segment;
segment = undefined;
}
if (v === undefined) {
segments = this.segment(segment, v, build);
if (!isArray(segments)) {
segments = segments !== undefined ? URI.decode(segments) : undefined;
} else {
for (i = 0, l = segments.length; i < l; i++) {
segments[i] = URI.decode(segments[i]);
}
}
return segments;
}
if (!isArray(v)) {
v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v;
} else {
for (i = 0, l = v.length; i < l; i++) {
v[i] = URI.encode(v[i]);
}
}
return this.segment(segment, v, build);
};
// mutating query string
var q = p.query;
p.query = function(v, build) {
if (v === true) {
return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
} else if (typeof v === 'function') {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
var result = v.call(this, data);
this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
this.build(!build);
return this;
} else if (v !== undefined && typeof v !== 'string') {
this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
this.build(!build);
return this;
} else {
return q.call(this, v, build);
}
};
p.setQuery = function(name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
if (typeof name === 'string' || name instanceof String) {
data[name] = value !== undefined ? value : null;
} else if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
data[key] = name[key];
}
}
} else {
throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
}
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.addQuery = function(name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
URI.addQuery(data, name, value === undefined ? null : value);
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.removeQuery = function(name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
URI.removeQuery(data, name, value);
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.hasQuery = function(name, value, withinArray) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
return URI.hasQuery(data, name, value, withinArray);
};
p.setSearch = p.setQuery;
p.addSearch = p.addQuery;
p.removeSearch = p.removeQuery;
p.hasSearch = p.hasQuery;
// sanitizing URLs
p.normalize = function() {
if (this._parts.urn) {
return this
.normalizeProtocol(false)
.normalizePath(false)
.normalizeQuery(false)
.normalizeFragment(false)
.build();
}
return this
.normalizeProtocol(false)
.normalizeHostname(false)
.normalizePort(false)
.normalizePath(false)
.normalizeQuery(false)
.normalizeFragment(false)
.build();
};
p.normalizeProtocol = function(build) {
if (typeof this._parts.protocol === 'string') {
this._parts.protocol = this._parts.protocol.toLowerCase();
this.build(!build);
}
return this;
};
p.normalizeHostname = function(build) {
if (this._parts.hostname) {
if (this.is('IDN') && punycode) {
this._parts.hostname = punycode.toASCII(this._parts.hostname);
} else if (this.is('IPv6') && IPv6) {
this._parts.hostname = IPv6.best(this._parts.hostname);
}
this._parts.hostname = this._parts.hostname.toLowerCase();
this.build(!build);
}
return this;
};
p.normalizePort = function(build) {
// remove port of it's the protocol's default
if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) {
this._parts.port = null;
this.build(!build);
}
return this;
};
p.normalizePath = function(build) {
var _path = this._parts.path;
if (!_path) {
return this;
}
if (this._parts.urn) {
this._parts.path = URI.recodeUrnPath(this._parts.path);
this.build(!build);
return this;
}
if (this._parts.path === '/') {
return this;
}
_path = URI.recodePath(_path);
var _was_relative;
var _leadingParents = '';
var _parent, _pos;
// handle relative paths
if (_path.charAt(0) !== '/') {
_was_relative = true;
_path = '/' + _path;
}
// handle relative files (as opposed to directories)
if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') {
_path += '/';
}
// resolve simples
_path = _path
.replace(/(\/(\.\/)+)|(\/\.$)/g, '/')
.replace(/\/{2,}/g, '/');
// remember leading parents
if (_was_relative) {
_leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || '';
if (_leadingParents) {
_leadingParents = _leadingParents[0];
}
}
// resolve parents
while (true) {
_parent = _path.search(/\/\.\.(\/|$)/);
if (_parent === -1) {
// no more ../ to resolve
break;
} else if (_parent === 0) {
// top level cannot be relative, skip it
_path = _path.substring(3);
continue;
}
_pos = _path.substring(0, _parent).lastIndexOf('/');
if (_pos === -1) {
_pos = _parent;
}
_path = _path.substring(0, _pos) + _path.substring(_parent + 3);
}
// revert to relative
if (_was_relative && this.is('relative')) {
_path = _leadingParents + _path.substring(1);
}
this._parts.path = _path;
this.build(!build);
return this;
};
p.normalizePathname = p.normalizePath;
p.normalizeQuery = function(build) {
if (typeof this._parts.query === 'string') {
if (!this._parts.query.length) {
this._parts.query = null;
} else {
this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace));
}
this.build(!build);
}
return this;
};
p.normalizeFragment = function(build) {
if (!this._parts.fragment) {
this._parts.fragment = null;
this.build(!build);
}
return this;
};
p.normalizeSearch = p.normalizeQuery;
p.normalizeHash = p.normalizeFragment;
p.iso8859 = function() {
// expect unicode input, iso8859 output
var e = URI.encode;
var d = URI.decode;
URI.encode = escape;
URI.decode = decodeURIComponent;
try {
this.normalize();
} finally {
URI.encode = e;
URI.decode = d;
}
return this;
};
p.unicode = function() {
// expect iso8859 input, unicode output
var e = URI.encode;
var d = URI.decode;
URI.encode = strictEncodeURIComponent;
URI.decode = unescape;
try {
this.normalize();
} finally {
URI.encode = e;
URI.decode = d;
}
return this;
};
p.readable = function() {
var uri = this.clone();
// removing username, password, because they shouldn't be displayed according to RFC 3986
uri.username('').password('').normalize();
var t = '';
if (uri._parts.protocol) {
t += uri._parts.protocol + '://';
}
if (uri._parts.hostname) {
if (uri.is('punycode') && punycode) {
t += punycode.toUnicode(uri._parts.hostname);
if (uri._parts.port) {
t += ':' + uri._parts.port;
}
} else {
t += uri.host();
}
}
if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') {
t += '/';
}
t += uri.path(true);
if (uri._parts.query) {
var q = '';
for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) {
var kv = (qp[i] || '').split('=');
q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace)
.replace(/&/g, '%26');
if (kv[1] !== undefined) {
q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace)
.replace(/&/g, '%26');
}
}
t += '?' + q.substring(1);
}
t += URI.decodeQuery(uri.hash(), true);
return t;
};
// resolving relative and absolute URLs
p.absoluteTo = function(base) {
var resolved = this.clone();
var properties = ['protocol', 'username', 'password', 'hostname', 'port'];
var basedir, i, p;
if (this._parts.urn) {
throw new Error('URNs do not have any generally defined hierarchical components');
}
if (!(base instanceof URI)) {
base = new URI(base);
}
if (resolved._parts.protocol) {
// Directly returns even if this._parts.hostname is empty.
return resolved;
} else {
resolved._parts.protocol = base._parts.protocol;
}
if (this._parts.hostname) {
return resolved;
}
for (i = 0; (p = properties[i]); i++) {
resolved._parts[p] = base._parts[p];
}
if (!resolved._parts.path) {
resolved._parts.path = base._parts.path;
if (!resolved._parts.query) {
resolved._parts.query = base._parts.query;
}
} else {
if (resolved._parts.path.substring(-2) === '..') {
resolved._parts.path += '/';
}
if (resolved.path().charAt(0) !== '/') {
basedir = base.directory();
basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : '';
resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path;
resolved.normalizePath();
}
}
resolved.build();
return resolved;
};
p.relativeTo = function(base) {
var relative = this.clone().normalize();
var relativeParts, baseParts, common, relativePath, basePath;
if (relative._parts.urn) {
throw new Error('URNs do not have any generally defined hierarchical components');
}
base = new URI(base).normalize();
relativeParts = relative._parts;
baseParts = base._parts;
relativePath = relative.path();
basePath = base.path();
if (relativePath.charAt(0) !== '/') {
throw new Error('URI is already relative');
}
if (basePath.charAt(0) !== '/') {
throw new Error('Cannot calculate a URI relative to another relative URI');
}
if (relativeParts.protocol === baseParts.protocol) {
relativeParts.protocol = null;
}
if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) {
return relative.build();
}
if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) {
return relative.build();
}
if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) {
relativeParts.hostname = null;
relativeParts.port = null;
} else {
return relative.build();
}
if (relativePath === basePath) {
relativeParts.path = '';
return relative.build();
}
// determine common sub path
common = URI.commonPath(relativePath, basePath);
// If the paths have nothing in common, return a relative URL with the absolute path.
if (!common) {
return relative.build();
}
var parents = baseParts.path
.substring(common.length)
.replace(/[^\/]*$/, '')
.replace(/.*?\//g, '../');
relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './';
return relative.build();
};
// comparing URIs
p.equals = function(uri) {
var one = this.clone();
var two = new URI(uri);
var one_map = {};
var two_map = {};
var checked = {};
var one_query, two_query, key;
one.normalize();
two.normalize();
// exact match
if (one.toString() === two.toString()) {
return true;
}
// extract query string
one_query = one.query();
two_query = two.query();
one.query('');
two.query('');
// definitely not equal if not even non-query parts match
if (one.toString() !== two.toString()) {
return false;
}
// query parameters have the same length, even if they're permuted
if (one_query.length !== two_query.length) {
return false;
}
one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace);
two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace);
for (key in one_map) {
if (hasOwn.call(one_map, key)) {
if (!isArray(one_map[key])) {
if (one_map[key] !== two_map[key]) {
return false;
}
} else if (!arraysEqual(one_map[key], two_map[key])) {
return false;
}
checked[key] = true;
}
}
for (key in two_map) {
if (hasOwn.call(two_map, key)) {
if (!checked[key]) {
// two contains a parameter not present in one
return false;
}
}
}
return true;
};
// state
p.preventInvalidHostname = function(v) {
this._parts.preventInvalidHostname = !!v;
return this;
};
p.duplicateQueryParameters = function(v) {
this._parts.duplicateQueryParameters = !!v;
return this;
};
p.escapeQuerySpace = function(v) {
this._parts.escapeQuerySpace = !!v;
return this;
};
return URI;
}));
/***/ }),
/***/ 132:
/***/ (function(module, exports, __webpack_require__) {
/* module decorator */ module = __webpack_require__.nmd(module);
var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.0 by @mathias */
;(function(root) {
/** Detect free variables */
var freeExports = true && exports &&
!exports.nodeType && exports;
var freeModule = true && module &&
!module.nodeType && module;
var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g;
if (
freeGlobal.global === freeGlobal ||
freeGlobal.window === freeGlobal ||
freeGlobal.self === freeGlobal
) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
var result = [];
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's state to ,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.3.2',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
true
) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
return punycode;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}(this));
/***/ }),
/***/ 221:
/***/ ((module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = isFQDN;
var _assertString = _interopRequireDefault(__webpack_require__(571));
var _merge = _interopRequireDefault(__webpack_require__(808));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var default_fqdn_options = {
require_tld: true,
allow_underscores: false,
allow_trailing_dot: false,
allow_numeric_tld: false,
allow_wildcard: false,
ignore_max_length: false
};
function isFQDN(str, options) {
(0, _assertString.default)(str);
options = (0, _merge.default)(options, default_fqdn_options);
/* Remove the optional trailing dot before checking validity */
if (options.allow_trailing_dot && str[str.length - 1] === '.') {
str = str.substring(0, str.length - 1);
}
/* Remove the optional wildcard before checking validity */
if (options.allow_wildcard === true && str.indexOf('*.') === 0) {
str = str.substring(2);
}
var parts = str.split('.');
var tld = parts[parts.length - 1];
if (options.require_tld) {
// disallow fqdns without tld
if (parts.length < 2) {
return false;
}
if (!options.allow_numeric_tld && !/^([a-z\u00A1-\u00A8\u00AA-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) {
return false;
} // disallow spaces
if (/\s/.test(tld)) {
return false;
}
} // reject numeric TLDs
if (!options.allow_numeric_tld && /^\d+$/.test(tld)) {
return false;
}
return parts.every(function (part) {
if (part.length > 63 && !options.ignore_max_length) {
return false;
}
if (!/^[a-z_\u00a1-\uffff0-9-]+$/i.test(part)) {
return false;
} // disallow full-width chars
if (/[\uff01-\uff5e]/.test(part)) {
return false;
} // disallow parts starting or ending with hyphen
if (/^-|-$/.test(part)) {
return false;
}
if (!options.allow_underscores && /_/.test(part)) {
return false;
}
return true;
});
}
module.exports = exports.default;
module.exports["default"] = exports.default;
/***/ }),
/***/ 28:
/***/ ((module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = isIP;
var _assertString = _interopRequireDefault(__webpack_require__(571));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
11.3. Examples
The following addresses
fe80::1234 (on the 1st link of the node)
ff02::5678 (on the 5th link of the node)
ff08::9abc (on the 10th organization of the node)
would be represented as follows:
fe80::1234%1
ff02::5678%5
ff08::9abc%10
(Here we assume a natural translation from a zone index to the
part, where the Nth zone of any scope is translated into
"N".)
If we use interface names as , those addresses could also be
represented as follows:
fe80::1234%ne0
ff02::5678%pvc1.3
ff08::9abc%interface10
where the interface "ne0" belongs to the 1st link, "pvc1.3" belongs
to the 5th link, and "interface10" belongs to the 10th organization.
* * */
var IPv4SegmentFormat = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
var IPv4AddressFormat = "(".concat(IPv4SegmentFormat, "[.]){3}").concat(IPv4SegmentFormat);
var IPv4AddressRegExp = new RegExp("^".concat(IPv4AddressFormat, "$"));
var IPv6SegmentFormat = '(?:[0-9a-fA-F]{1,4})';
var IPv6AddressRegExp = new RegExp('^(' + "(?:".concat(IPv6SegmentFormat, ":){7}(?:").concat(IPv6SegmentFormat, "|:)|") + "(?:".concat(IPv6SegmentFormat, ":){6}(?:").concat(IPv4AddressFormat, "|:").concat(IPv6SegmentFormat, "|:)|") + "(?:".concat(IPv6SegmentFormat, ":){5}(?::").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,2}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){4}(?:(:").concat(IPv6SegmentFormat, "){0,1}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,3}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){3}(?:(:").concat(IPv6SegmentFormat, "){0,2}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,4}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){2}(?:(:").concat(IPv6SegmentFormat, "){0,3}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,5}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){1}(?:(:").concat(IPv6SegmentFormat, "){0,4}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,6}|:)|") + "(?::((?::".concat(IPv6SegmentFormat, "){0,5}:").concat(IPv4AddressFormat, "|(?::").concat(IPv6SegmentFormat, "){1,7}|:))") + ')(%[0-9a-zA-Z-.:]{1,})?$');
function isIP(str) {
var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
(0, _assertString.default)(str);
version = String(version);
if (!version) {
return isIP(str, 4) || isIP(str, 6);
}
if (version === '4') {
return IPv4AddressRegExp.test(str);
}
if (version === '6') {
return IPv6AddressRegExp.test(str);
}
return false;
}
module.exports = exports.default;
module.exports["default"] = exports.default;
/***/ }),
/***/ 492:
/***/ ((module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = isURL;
var _assertString = _interopRequireDefault(__webpack_require__(571));
var _isFQDN = _interopRequireDefault(__webpack_require__(221));
var _isIP = _interopRequireDefault(__webpack_require__(28));
var _merge = _interopRequireDefault(__webpack_require__(808));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
/*
options for isURL method
require_protocol - if set as true isURL will return false if protocol is not present in the URL
require_valid_protocol - isURL will check if the URL's protocol is present in the protocols option
protocols - valid protocols can be modified with this option
require_host - if set as false isURL will not check if host is present in the URL
require_port - if set as true isURL will check if port is present in the URL
allow_protocol_relative_urls - if set as true protocol relative URLs will be allowed
validate_length - if set as false isURL will skip string length validation (IE maximum is 2083)
*/
var default_url_options = {
protocols: ['http', 'https', 'ftp'],
require_tld: true,
require_protocol: false,
require_host: true,
require_port: false,
require_valid_protocol: true,
allow_underscores: false,
allow_trailing_dot: false,
allow_protocol_relative_urls: false,
allow_fragments: true,
allow_query_components: true,
validate_length: true
};
var wrapped_ipv6 = /^\[([^\]]+)\](?::([0-9]+))?$/;
function isRegExp(obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
}
function checkHost(host, matches) {
for (var i = 0; i < matches.length; i++) {
var match = matches[i];
if (host === match || isRegExp(match) && match.test(host)) {
return true;
}
}
return false;
}
function isURL(url, options) {
(0, _assertString.default)(url);
if (!url || /[\s<>]/.test(url)) {
return false;
}
if (url.indexOf('mailto:') === 0) {
return false;
}
options = (0, _merge.default)(options, default_url_options);
if (options.validate_length && url.length >= 2083) {
return false;
}
if (!options.allow_fragments && url.includes('#')) {
return false;
}
if (!options.allow_query_components && (url.includes('?') || url.includes('&'))) {
return false;
}
var protocol, auth, host, hostname, port, port_str, split, ipv6;
split = url.split('#');
url = split.shift();
split = url.split('?');
url = split.shift();
split = url.split('://');
if (split.length > 1) {
protocol = split.shift().toLowerCase();
if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) {
return false;
}
} else if (options.require_protocol) {
return false;
} else if (url.slice(0, 2) === '//') {
if (!options.allow_protocol_relative_urls) {
return false;
}
split[0] = url.slice(2);
}
url = split.join('://');
if (url === '') {
return false;
}
split = url.split('/');
url = split.shift();
if (url === '' && !options.require_host) {
return true;
}
split = url.split('@');
if (split.length > 1) {
if (options.disallow_auth) {
return false;
}
if (split[0] === '') {
return false;
}
auth = split.shift();
if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) {
return false;
}
var _auth$split = auth.split(':'),
_auth$split2 = _slicedToArray(_auth$split, 2),
user = _auth$split2[0],
password = _auth$split2[1];
if (user === '' && password === '') {
return false;
}
}
hostname = split.join('@');
port_str = null;
ipv6 = null;
var ipv6_match = hostname.match(wrapped_ipv6);
if (ipv6_match) {
host = '';
ipv6 = ipv6_match[1];
port_str = ipv6_match[2] || null;
} else {
split = hostname.split(':');
host = split.shift();
if (split.length) {
port_str = split.join(':');
}
}
if (port_str !== null && port_str.length > 0) {
port = parseInt(port_str, 10);
if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) {
return false;
}
} else if (options.require_port) {
return false;
}
if (options.host_whitelist) {
return checkHost(host, options.host_whitelist);
}
if (host === '' && !options.require_host) {
return true;
}
if (!(0, _isIP.default)(host) && !(0, _isFQDN.default)(host, options) && (!ipv6 || !(0, _isIP.default)(ipv6, 6))) {
return false;
}
host = host || ipv6;
if (options.host_blacklist && checkHost(host, options.host_blacklist)) {
return false;
}
return true;
}
module.exports = exports.default;
module.exports["default"] = exports.default;
/***/ }),
/***/ 571:
/***/ ((module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = assertString;
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function assertString(input) {
var isString = typeof input === 'string' || input instanceof String;
if (!isString) {
var invalidType = _typeof(input);
if (input === null) invalidType = 'null';else if (invalidType === 'object') invalidType = input.constructor.name;
throw new TypeError("Expected a string but received a ".concat(invalidType));
}
}
module.exports = exports.default;
module.exports["default"] = exports.default;
/***/ }),
/***/ 808:
/***/ ((module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = merge;
function merge() {
var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var defaults = arguments.length > 1 ? arguments[1] : undefined;
for (var key in defaults) {
if (typeof obj[key] === 'undefined') {
obj[key] = defaults[key];
}
}
return obj;
}
module.exports = exports.default;
module.exports["default"] = exports.default;
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ id: moduleId,
/******/ loaded: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ (() => {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = (module) => {
/******/ var getter = module && module.__esModule ?
/******/ () => (module['default']) :
/******/ () => (module);
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ })();
/******/
/******/ /* 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/global */
/******/ (() => {
/******/ __webpack_require__.g = (function() {
/******/ if (typeof globalThis === 'object') return globalThis;
/******/ try {
/******/ return this || new Function('return this')();
/******/ } catch (e) {
/******/ if (typeof window === 'object') return window;
/******/ }
/******/ })();
/******/ })();
/******/
/******/ /* webpack/runtime/harmony module decorator */
/******/ (() => {
/******/ __webpack_require__.hmd = (module) => {
/******/ module = Object.create(module);
/******/ if (!module.children) module.children = [];
/******/ Object.defineProperty(module, 'exports', {
/******/ enumerable: true,
/******/ set: () => {
/******/ throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);
/******/ }
/******/ });
/******/ return module;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/node module decorator */
/******/ (() => {
/******/ __webpack_require__.nmd = (module) => {
/******/ module.paths = [];
/******/ if (!module.children) module.children = [];
/******/ return module;
/******/ };
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(294);
// EXTERNAL MODULE: ./node_modules/react-dom/index.js
var react_dom = __webpack_require__(935);
;// CONCATENATED MODULE: ./src/components/DebuggingUtils.js
class DebuggingUtils_Home extends react.Component {
triggerCrash = () => {
if (false) {}
};
render() {
if (false) {}
return null;
}
}
;// CONCATENATED MODULE: ./src/components/DisableButton.js
/* harmony default export */ const DisableButton = (({
sessionWhitelist,
currentUrl,
onSiteDisable,
onSiteEnable,
bdLang
}) => {
let currentState = true;
let currentCallback = onSiteDisable;
if (undefined != sessionWhitelist && sessionWhitelist.includes(currentUrl)) {
currentState = false;
currentCallback = onSiteEnable;
}
return /*#__PURE__*/react.createElement("div", null, /*#__PURE__*/react.createElement("label", {
className: "play-pause"
}, /*#__PURE__*/react.createElement("input", {
type: "checkbox",
checked: currentState,
onChange: currentCallback
}), /*#__PURE__*/react.createElement("div", null, /*#__PURE__*/react.createElement("span", null, bdLang.getString("pause_protection")), /*#__PURE__*/react.createElement("span", null, bdLang.getString("enable_protection")))), /*#__PURE__*/react.createElement("div", {
className: "enable-shadow"
}, bdLang.getString("enable_app")));
});
// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js
var src_URI = __webpack_require__(998);
var URI_default = /*#__PURE__*/__webpack_require__.n(src_URI);
;// CONCATENATED MODULE: ./src/utils/parseUrl.js
/* harmony default export */ const utils_parseUrl = (url => {
if (null === url || '' === url) {
return {
schema: '',
hostname: '',
port: '',
pathname: '',
search: '',
hash: ''
};
}
try {
var uri = new (URI_default())(url);
return {
schema: uri.protocol(),
hostname: uri.hostname(),
port: uri.port(),
pathname: uri.pathname(),
search: uri.search(),
hash: uri.hash()
};
} catch (ex) {}
return {
schema: '',
hostname: '',
port: '',
pathname: '',
search: '',
hash: ''
};
});
// EXTERNAL MODULE: ./node_modules/debug/src/browser.js
var browser = __webpack_require__(227);
var browser_default = /*#__PURE__*/__webpack_require__.n(browser);
;// CONCATENATED MODULE: ./src/logger/log.js
const BASE = 'bdat';
const COLOURS = {
trace: 'lightblue',
info: 'purple',
warn: 'orange',
error: 'red'
};
class BdLogging {
constructor() {}
restore() {
chrome.storage.local.get('debug', value => {
if (value) {
if (value.hasOwnProperty('debug')) {
let namespace = value['debug'];
browser_default().enable(namespace);
}
}
});
}
disable() {
chrome.storage.local.remove('debug');
browser_default().disable();
}
enable() {
chrome.storage.local.set({
'debug': 'bdat:*'
});
browser_default().enable('bdat:*');
}
}
var bdLogging = self.bdLogging = new BdLogging();
if (false) {} else {
bdLogging.restore();
}
class log_Log {
constructor() {
this.source = null;
}
init(source) {
this.source = source;
}
generateMessage(level, message) {
// Set the prefix which will cause debug to enable the message
const namespace = `${BASE}:${level}`;
const createDebug = browser_default()(namespace);
// Set the colour of the message based on the level
createDebug.color = COLOURS[level];
if (this.source) {
createDebug(this.source, message);
} else {
createDebug(message);
}
}
trace(message) {
return this.generateMessage('trace', message);
}
info(message) {
return this.generateMessage('info', message);
}
warn(message) {
return this.generateMessage('warn', message);
}
error(message) {
return this.generateMessage('error', message);
}
}
/* harmony default export */ const log = (new log_Log());
// EXTERNAL MODULE: ./src/tracking/tracking.js
var tracking_tracking = __webpack_require__(146);
var tracking_default = /*#__PURE__*/__webpack_require__.n(tracking_tracking);
;// CONCATENATED MODULE: ./src/scripts/compat.js
/**
* Manifest v3 and v2 compatibility
*/
class compat_compat {
constructor() {
this.action = this.getBrowserAction();
this.dnr = {
available: this.getDnrAvailable(),
debug: {
available: this.getDnrDebugAvailable()
},
action: {
available: this.getDnrActionAvailable()
},
rules: {
rulesets: {
available: this.getDnrRulesetsAvailable()
},
dynamic: {
available: this.getDnrDynamicRulesAvailable()
},
session: {
available: this.getDnrSessionRulesAvailable()
}
},
declarativeNetRequest: this.getDnrApi()
};
}
getDnrApi = () => {
if (true) {
if (typeof chrome.declarativeNetRequest !== 'undefined') return chrome.declarativeNetRequest;
}
return undefined;
};
getDnrAvailable = () => {
return typeof this.getDnrApi() !== 'undefined';
};
getDnrDebugAvailable = () => {
return this.getDnrAvailable() && typeof this.getDnrApi().onRuleMatchedDebug !== 'undefined';
};
getDnrActionAvailable = () => {
return this.getDnrAvailable() && typeof this.getDnrApi().setExtensionActionOptions !== 'undefined';
};
getDnrRulesetsAvailable = () => {
return this.getDnrAvailable() && typeof this.getDnrApi().updateEnabledRulesets !== 'undefined';
};
getDnrDynamicRulesAvailable = () => {
return this.getDnrAvailable() && typeof this.getDnrApi().updateDynamicRules !== 'undefined';
};
getDnrSessionRulesAvailable = () => {
return this.getDnrAvailable() && typeof this.getDnrApi().updateSessionRules !== 'undefined';
};
getBrowserAction = () => {
if (typeof chrome.action !== 'undefined') {
return chrome.action;
}
if (typeof chrome.browserAction !== 'undefined') {
return chrome.browserAction;
}
return null;
};
executeScript(tabId, frameIds, files, callback) {
if (typeof chrome.scripting !== 'undefined') {
chrome.scripting.executeScript({
target: {
tabId: tabId,
frameIds: frameIds
},
files: files
}, callback);
return;
}
if (typeof chrome.tabs.executeScript !== 'undefined') {
frameIds.forEach(frameId => {
files.forEach(file => {
chrome.tabs.executeScript(tabId, {
file: file,
frameId: frameId
}, callback);
});
});
return;
}
}
}
/* harmony default export */ const scripts_compat = (new compat_compat());
;// CONCATENATED MODULE: ./src/utils/helpers.js
/**
* helpers functions
*/
//chrome.extension.getBackgroundPage().
function CategoryInfo() {
this.name = '';
this.blocked = '';
this.icon = '';
this.className = '';
}
function setCategoryInfo(bdLang, catTitle, pageTitle, catIcon, catClassName) {
let catInfo = new CategoryInfo();
catInfo.name = bdLang.getString(catTitle);
catInfo.blocked = bdLang.getString(pageTitle);
catInfo.icon = catIcon;
catInfo.className = catClassName;
return catInfo;
}
function setCategoryStatus(bdLang, catStatus, catEnabled, catDisabled) {
let status = '';
if (catStatus) {
status = bdLang.getString(catEnabled);
} else {
status = bdLang.getString(catDisabled);
}
return status;
}
/**
* get trackers category name
* @param {*} trackerCategoryType
*/
function getTrackerCategoryName(bdLang, trackerCategoryType) {
let catInfo = new CategoryInfo();
switch (trackerCategoryType) {
case '1':
{
catInfo = setCategoryInfo(bdLang, 'advertising_category_title', 'advertising_page_title', 'advertising-icon', 'category-trackers-list advertising');
break;
}
case '2':
{
catInfo = setCategoryInfo(bdLang, 'analytics_category_title', 'analytics_page_title', 'analytics-icon', 'category-trackers-list analytics');
break;
}
case '4':
{
catInfo = setCategoryInfo(bdLang, 'interaction_category_title', 'interaction_page_title', 'customer-icon', 'category-trackers-list customer');
break;
}
case '8':
{
catInfo = setCategoryInfo(bdLang, 'social_category_title', 'social_page_title', 'social-icon', 'category-trackers-list social');
break;
}
case '16':
{
catInfo = setCategoryInfo(bdLang, 'essential_category_title', 'essential_page_title', 'essentials-icon', 'category-trackers-list essentials');
break;
}
case '32':
{
catInfo = setCategoryInfo(bdLang, 'cookies_category_title', 'cookies_page_title', 'cookies-icon', 'category-trackers-list cookies');
break;
}
}
return catInfo;
}
/**
* getTrackerCategoryDescription
* @param {*} trackerCategoryType
*/
function getTrackerCategoryDescription(bdLang, trackerCategoryType) {
let description = '';
switch (trackerCategoryType) {
case '1':
{
description = bdLang.getString("advertising_category_desc");
break;
}
case '2':
{
description = bdLang.getString("analytics_category_desc");
break;
}
case '4':
{
description = bdLang.getString("interaction_category_desc");
break;
}
case '8':
{
description = bdLang.getString("social_category_desc");
break;
}
case '16':
{
description = bdLang.getString("essential_category_desc");
break;
}
case '32':
{
description = bdLang.getString("cookies_category_desc");
break;
}
}
return description;
}
/**
* getTrackerCategoryTooltip
* @param {*} trackerCategoryType
*/
function getTrackerCategoryTooltip(bdLang, trackerCategoryType) {
let tooltip = '';
switch (trackerCategoryType) {
case '1':
{
tooltip = bdLang.getString("advertising_category_tooltip");
break;
}
case '2':
{
tooltip = bdLang.getString("analytics_category_tooltip");
break;
}
case '4':
{
tooltip = bdLang.getString("interaction_category_tooltip");
break;
}
case '8':
{
tooltip = bdLang.getString("social_category_tooltip");
break;
}
case '16':
{
tooltip = bdLang.getString("essential_category_tooltip");
break;
}
case '32':
{
tooltip = bdLang.getString("cookies_category_tooltip");
break;
}
}
return tooltip;
}
/**
* getTrackerCategoryStatus
* @param {*} trackerCategoryStatus
*/
function getTrackerCategoryStatus(bdLang, trackerCategoryType, trackerCategoryStatus) {
let status = '';
switch (trackerCategoryType) {
case '1':
{
status = setCategoryStatus(bdLang, trackerCategoryStatus, 'advertising_page_button_block', 'advertising_page_button_unblock');
break;
}
case '2':
{
status = setCategoryStatus(bdLang, trackerCategoryStatus, 'analytics_page_button_block', 'analytics_page_button_unblock');
break;
}
case '4':
{
status = setCategoryStatus(bdLang, trackerCategoryStatus, 'interaction_page_button_block', 'interaction_page_button_unblock');
break;
}
case '8':
{
status = setCategoryStatus(bdLang, trackerCategoryStatus, 'social_page_button_block', 'social_page_button_unblock');
break;
}
case '16':
{
status = setCategoryStatus(bdLang, trackerCategoryStatus, 'essential_page_button_block', 'essential_page_button_unblock');
break;
}
case '32':
{
status = setCategoryStatus(bdLang, trackerCategoryStatus, 'cookies_page_button_block', 'cookies_page_button_unblock');
break;
}
}
return status;
}
function getTrackerPieCountText(trackersBlocked) {
if (trackersBlocked >= 99000) return "99k";
if (trackersBlocked >= 1000) return Math.floor(trackersBlocked / 1000) + "k";
return trackersBlocked.toString();
}
function setBadgeColor() {
compat.action.setBadgeBackgroundColor({
color: "rgb(0,0,255)"
});
}
/* setBadgeMessage
* @param {*} currentTabId, nrTrackers
*/
function setBadgeMessage(currentTabId, nrTrackers) {
compat.action.setBadgeText({
text: nrTrackers.toString(),
tabId: currentTabId
});
}
function clearBadgeMessage(currentTabId) {
compat.action.setBadgeText({
text: "",
tabId: currentTabId
});
}
function getBadgeMessage(currentTabId, callback) {
scripts_compat.action.getBadgeText({
tabId: currentTabId
}, result => {
callback(result);
});
}
function dnrSetBadgeMessageFromMatchedRules(currentTabId) {
if (compat.dnr.available) {
Log.warn('[dnr] v3 dnrSetBadgeMessageFromMatchedRules');
compat.dnr.declarativeNetRequest.getMatchedRules({
tabId: currentTabId
}, rulesMatchedDetails => {
if (rulesMatchedDetails) {
Log.warn('[dnr] dnrSetBadgeMessageFromMatchedRules: ' + JSON.stringify(rulesMatchedDetails, null, 4));
let trackersBlocked = 0;
rulesMatchedDetails.rulesMatchedInfo.forEach(match => {
switch (tracking.categoryStringToId(match.rule.rulesetId)) {
case tracking.categories.ADS:
trackersBlocked++;
break;
case tracking.categories.SITE_ANALYTICS:
trackersBlocked++;
break;
case tracking.categories.CUSTOMER_INTERACTION:
trackersBlocked++;
break;
case tracking.categories.SOCIAL_MEDIA:
trackersBlocked++;
break;
case tracking.categories.ESSENTIAL:
trackersBlocked++;
break;
case tracking.categories.COOKIE:
trackersBlocked++;
break;
}
});
if (trackersBlocked > 0) {
setBadgeMessage(currentTabId, trackersBlocked);
} else {
clearBadgeMessage(currentTabId);
}
}
});
}
}
const TAB_INFO_TRANSITION = {
COMMITED: 1,
PROVISIONAL: 2
};
function copyTabInfo(inputTabInfo) {
let outputTabInfo = {
'transition': TAB_INFO_TRANSITION.COMMITED,
'url': '',
'trackersBlocked': 0,
'pageLoad': 0,
'pageLoadStartTime': 0,
'trackersMap': {},
'trackersUrls': []
};
if (inputTabInfo !== undefined) {
outputTabInfo = {
'transition': inputTabInfo.transition,
'url': inputTabInfo.url,
'trackersBlocked': inputTabInfo.trackersBlocked,
'pageLoad': inputTabInfo.pageLoad,
'pageLoadStartTime': inputTabInfo.pageLoadStartTime,
'trackersMap': inputTabInfo.trackersMap,
'trackersUrls': inputTabInfo.trackersUrls
};
}
return outputTabInfo;
}
function copyTabStack(inputTabStack) {
let outputTabStack = [];
if (inputTabStack !== undefined) {
for (let i = 0; i < inputTabStack.length; i++) {
let outputTabInfo = copyTabInfo(inputTabStack[i]);
outputTabStack[i] = outputTabInfo;
}
}
return outputTabStack;
}
function getTabStackTrackersBlocked(inputTabStack) {
let trackersBlocked = 0;
if (inputTabStack !== undefined) {
for (let i = 0; i < inputTabStack.length; i++) {
trackersBlocked += inputTabStack[i].trackersBlocked;
}
}
return trackersBlocked;
}
/* updateUiStack
* @param {*} tabId, inputTabStack, whitelist
*/
function updateUiStack(tabId, inputTabStack, whitelist) {
chrome.tabs.query({
active: true,
currentWindow: true
}, tabs => {
if (!tabs || !tabs.length) {
return;
}
if (null != tabs && null != tabs[0]) {
if (tabId === tabs[0].id && null != inputTabStack) {
let inputTabInfo = inputTabStack[0];
if (null != inputTabInfo) {
let trackersBlocked = getTabStackTrackersBlocked(inputTabStack);
let objectTabStack = copyTabStack(inputTabStack);
if (canBlockWebRequest()) {
setBadgeMessage(tabId, trackersBlocked);
}
chrome.runtime.sendMessage({
type: 'update_tab_stack',
tabStack: objectTabStack,
sessionWhitelist: whitelist
}, () => {
//need to check lastError to prevent error being displayed in the
//browser extension page when there is no content script loaded in tab
chrome.runtime.lastError;
});
}
}
}
});
}
/* updateUiLoadTime
* @param {*} tabId, inputTabStack
*/
function updateUiPageLoad(tabId, inputTabStack) {
chrome.tabs.query({
active: true,
currentWindow: true
}, tabs => {
if (!tabs || !tabs.length) {
return;
}
if (null != tabs && null != tabs[0]) {
if (tabId === tabs[0].id && null != inputTabStack) {
let inputTabInfo = inputTabStack[0];
if (null != inputTabInfo) {
let objectTabStack = copyTabStack(inputTabStack);
chrome.runtime.sendMessage({
type: 'update_page_load',
tabStack: objectTabStack
}, () => {
//need to check lastError to prevent error being displayed in the
//browser extension page when there is no content script loaded in tab
chrome.runtime.lastError;
});
}
}
}
});
}
/* getTelemetryJson
* @param {*} telemetry_type, telemetry_value
*/
function getTelemetryJson(telemetry_type, telemetry_value) {
var telemetry_json = {
'method': 'send_telemetry',
'browser_context': getBrowserContext()
};
var telemetry_info = {
'type': telemetry_type,
'value': telemetry_value
};
telemetry_json['telemetry_info'] = telemetry_info;
return telemetry_json;
}
/* isBdTrackingIds
* @param tab_url: cirrent tab url
* @param scan_url: current scan url
*/
function isBdTrackingIds(tab_url, scan_url) {
let scan_url_lower = scan_url.toLowerCase();
if (tab_url.toLowerCase().includes('bitdefender') || scan_url_lower.includes('bitdefender')) {
return true;
}
if (scan_url_lower.includes('assets.adobedtm.com/launch-en6b51aa9552f941f88576315ed8766e3f')) {
return true;
}
if (scan_url_lower.includes('assets.adobedtm.com/4b7ac0a30c6cfe2deb06368f62d41f996c29744e/satelliteLib-3a8d5287cf775324dc6c68719a1ddc96c5a139ba')) {
return true;
}
if (scan_url_lower.includes('gtm-pljjb3') || scan_url_lower.includes('gtm-mq8rtn')) {
return true;
}
if (scan_url_lower.includes('assets.adobedtm.com/launch-ENa82c50bdc4c541bdb7d581931510efc5')) {
return true;
}
if (scan_url_lower.includes('assets.adobedtm.com/8a93f8486ba4/62c1fd5cdcbd/launch-b77a56f2d5f1')) {
return true;
}
if (scan_url_lower.includes('assets.adobedtm.com/8a93f8486ba4/0f17a64d87b7/launch-c3512379eccf')) {
return true;
}
if (scan_url_lower.includes('assets.adobedtm.com/8a93f8486ba4/5492896ad67e/launch-b1f76be4d2ee')) {
return true;
}
if (scan_url_lower.includes('assets.adobedtm.com/extensions/EP308220a2a4c4403f97fc1960100db40f/AppMeasurement')) {
return true;
}
if (scan_url_lower.includes('assets.adobedtm.com/extensions/EP308220a2a4c4403f97fc1960100db40f/AppMeasurement_Module_AudienceManagement')) {
return true;
}
if (scan_url_lower.includes('assets.adobedtm.com/extensions/EPef068a8d6dd34a43866d9a80cc98baab/AppMeasurement')) {
return true;
}
if (scan_url_lower.includes('assets.adobedtm.com/extensions/EPef068a8d6dd34a43866d9a80cc98baab/AppMeasurement_Module_ActivityMap')) {
return true;
}
if (scan_url_lower.includes('assets.adobedtm.com/8a93f8486ba4/df27e7ff35f3/6ad1b33eca05/RC22febb28520c43e3af9acfb4f9bfa34f')) {
return true;
}
return false;
}
/* TabInfo
* @param null
*/
function TabInfo() {
this.transition = TAB_INFO_TRANSITION.COMMITED;
this.url = '';
this.trackersBlocked = 0;
this.pageLoad = 0;
this.pageLoadStartTime = 0;
this.trackersMap = {};
this.trackersUrls = [];
}
const SCREEN_UI = {
MAIN: 1,
CATEGORY: 2,
SETTINGS: 4
};
const TELEMETRY_EVENT_TYPE = {
ENABLED: 0,
PAUSE: 1,
ADVERTISING: 2,
ANALYTICS: 3,
INTERACTION: 4,
SOCIAL_MEDIA: 5,
ESSENTIAL: 6,
SPECIAL_OFFERS: 7
};
const BROWSER_CONTEXT = {
BROWSER_CONTEXT_ALL: 0,
BROWSER_CONTEXT_CHROME: 1,
BROWSER_CONTEXT_FIREFOX: 2,
BROWSER_CONTEXT_EDGE_CHROMIUM: 3,
BROWSER_CONTEXT_IE: 4,
BROWSER_CONTEXT_IE64: 5,
BROWSER_CONTEXT_UNKNOWN: 6
};
/* getPathFromUrl
* @param {String} url
*/
function getPathFromUrl(url) {
return url.split(/[?#]/)[0];
}
function getTabUrl(url) {
if (undefined !== url) {
if (url.startsWith('file:')) {
return url;
} else {
return parseUrl(url).hostname;
}
}
return url;
}
function getBrowserContext() {
try {
let browserContextName = "chrome";
if (browserContextName.toLowerCase() === 'edge') {
return BROWSER_CONTEXT.BROWSER_CONTEXT_EDGE_CHROMIUM;
}
if (browserContextName.toLowerCase() === 'chrome') {
return BROWSER_CONTEXT.BROWSER_CONTEXT_CHROME;
}
if (browserContextName.toLowerCase() === 'firefox') {
return BROWSER_CONTEXT.BROWSER_CONTEXT_FIREFOX;
}
} catch (ex) {}
try {
let internalUrl = chrome.runtime.getURL("home.html");
if (internalUrl.toLowerCase().startsWith('moz-extension')) {
return BROWSER_CONTEXT.BROWSER_CONTEXT_FIREFOX;
}
if (internalUrl.toLowerCase().startsWith('extension://')) {
return BROWSER_CONTEXT.BROWSER_CONTEXT_EDGE_CHROMIUM;
}
if (internalUrl.toLowerCase().startsWith('chrome-extension://')) {
return BROWSER_CONTEXT.BROWSER_CONTEXT_CHROME;
}
return BROWSER_CONTEXT_EDGE_CHROMIUM;
} catch (ex) {}
if ('bdtbe@bitdefender.com' === chrome.runtime.id) {
return BROWSER_CONTEXT.BROWSER_CONTEXT_FIREFOX;
}
return BROWSER_CONTEXT.BROWSER_CONTEXT_UNKNOWN;
}
function canBlockWebRequest() {
const browserContext = getBrowserContext();
if (browserContext === BROWSER_CONTEXT.BROWSER_CONTEXT_CHROME || browserContext === BROWSER_CONTEXT.BROWSER_CONTEXT_EDGE_CHROMIUM) {
return false;
}
return true;
}
/**
*
* @param {String} host_name
*/
function getDomain(host_name) {
var uri = new URI(host_name);
if (uri.protocol() === '') {
uri = new URI('https://' + host_name);
}
var domain = uri.domain();
Log.info('getDomain: [' + host_name + '] [' + domain + ']');
return domain;
}
/**
*
* @param {String} request_host
* @param {String} tab_host
*/
function isThirdPartyDomain(request_host, tab_host) {
var ret = true;
if (null === request_host || null === tab_host) {
ret = false;
} else {
ret = getDomain(request_host) !== getDomain(tab_host);
}
if (ret) {
if (tracking.isThirdPartyDomainException(request_host, tab_host)) {
Log.info('isThirdPartyDomainException: [' + request_host + '] <- [' + tab_host + ']');
ret = false;
}
}
Log.info('isThirdPartyDomain: [' + request_host + '] <- [' + tab_host + '] [' + ret + ']');
return ret;
}
function replaceStringInObjectProperties(entity, regExp, replacement) {
for (let property in entity) {
if (!entity.hasOwnProperty(property)) {
continue;
}
let value = entity[property];
if (typeof value === "object") {
value = replaceStringInObjectProperties(value, regExp, replacement);
} else if (typeof value === "string") {
value = value.replace(regExp, replacement);
}
entity[property] = value;
}
return entity;
}
;// CONCATENATED MODULE: ./src/components/TrackersCategory.js
function getTrackerUrlHostname(url, trackersUrls) {
let hostName = url;
if (canBlockWebRequest()) {
hostName = utils_parseUrl(url).hostname;
return hostName;
}
if (trackersUrls.length > 0) {
let urlRegex = new RegExp(url);
for (let tIndex = 0; tIndex < trackersUrls.length; ++tIndex) {
let tUrl = trackersUrls[tIndex];
if (urlRegex.test(tUrl)) {
hostName = utils_parseUrl(tUrl).hostname;
return hostName;
}
}
}
let pos = hostName.indexOf('/');
if (pos > 0) {
hostName = hostName.substring(0, pos);
}
return hostName;
}
function displayTrackersUrls(trackersMap, trackersUrls, currentCategoryKey) {
let listItems = [];
if (undefined === trackersMap || undefined === trackersMap[currentCategoryKey] || null === trackersMap[currentCategoryKey]) {
return listItems;
}
log.warn('displayTrackersUrls trackersMap: ' + JSON.stringify(trackersMap, null, 4));
log.warn('displayTrackersUrls trackersUrls: ' + JSON.stringify(trackersUrls, null, 4));
function CatInfo(_url, _urlCount) {
this.url = _url;
this.urlCount = _urlCount;
}
let trackersUrlList = trackersMap[currentCategoryKey];
let trackersCatMap = new Map();
for (let index = 0; index < trackersUrlList.length; ++index) {
let url = trackersUrlList[index];
let hostName = getTrackerUrlHostname(url, trackersUrls);
if (hostName.length === 0) {
hostName = url;
}
if (trackersCatMap.has(hostName)) {
let catInfo = trackersCatMap.get(hostName);
catInfo.urlCount = catInfo.urlCount + 1;
trackersCatMap.set(hostName, catInfo);
} else {
let catInfo = new CatInfo(url, 1);
trackersCatMap.set(hostName, catInfo);
}
}
let indexKey = 0;
for (let [key, value] of trackersCatMap) {
listItems.push( /*#__PURE__*/react.createElement("li", {
key: indexKey
}, /*#__PURE__*/react.createElement("div", {
className: "name"
}, /*#__PURE__*/react.createElement("span", null, key), /*#__PURE__*/react.createElement("span", {
className: "count"
}, value.urlCount)), /*#__PURE__*/react.createElement("div", {
className: "url",
title: value.url
}, value.url)));
indexKey++;
}
return listItems;
}
/* harmony default export */ const TrackersCategory = (({
currentScreen,
currentCategoryKey,
categoryExpandRef,
categories,
trackersMap,
trackersUrls,
categoryStatusChanged,
onClickCategoryLink,
onClickBack,
bdLang
}) => {
if (currentScreen & SCREEN_UI.CATEGORY) {
log.info('current screen: ' + currentScreen + ' current category key: ' + currentCategoryKey);
let currentStatus = true;
if (categories & currentCategoryKey) {
currentStatus = false;
}
let categoryInfo = getTrackerCategoryName(bdLang, currentCategoryKey);
let nrTrackers = 0;
if (undefined !== trackersMap && undefined !== trackersMap[currentCategoryKey] && null !== trackersMap[currentCategoryKey]) {
nrTrackers = trackersMap[currentCategoryKey].length;
}
let categoryTitle = categoryInfo.blocked.replace("%d", nrTrackers);
let categoryButtonStatus = getTrackerCategoryStatus(bdLang, currentCategoryKey, currentStatus);
let linkDescriptionDisplay = false;
let catDescriptionText = getTrackerCategoryDescription(bdLang, currentCategoryKey);
log.info('desc size: ' + catDescriptionText.length);
if (catDescriptionText.length < 118) {
linkDescriptionDisplay = true;
}
return /*#__PURE__*/react.createElement("div", {
className: "category-screen show"
}, /*#__PURE__*/react.createElement("div", {
className: "dashboard _expand",
ref: categoryExpandRef
}, /*#__PURE__*/react.createElement("button", {
className: "back",
onClick: onClickBack
}), /*#__PURE__*/react.createElement("img", {
className: categoryInfo.icon
}), /*#__PURE__*/react.createElement("div", {
className: "category-title"
}, categoryTitle), /*#__PURE__*/react.createElement("div", {
className: "description"
}, catDescriptionText), /*#__PURE__*/react.createElement("div", {
hidden: linkDescriptionDisplay
}, /*#__PURE__*/react.createElement("a", {
onClick: onClickCategoryLink
}, /*#__PURE__*/react.createElement("span", null, bdLang.getString("show_more_details")), /*#__PURE__*/react.createElement("span", null, bdLang.getString("hide_more_details")))), /*#__PURE__*/react.createElement("br", null), /*#__PURE__*/react.createElement("label", {
className: "block-all"
}, /*#__PURE__*/react.createElement("input", {
type: "checkbox",
checked: currentStatus,
onChange: categoryStatusChanged
}), /*#__PURE__*/react.createElement("div", null, /*#__PURE__*/react.createElement("span", null, categoryButtonStatus), /*#__PURE__*/react.createElement("span", null, categoryButtonStatus)))), /*#__PURE__*/react.createElement("ul", {
className: categoryInfo.className
}, displayTrackersUrls(trackersMap, trackersUrls, currentCategoryKey)));
} else {
return null;
}
});
;// CONCATENATED MODULE: ./src/components/TrackersSettings.js
/* harmony default export */ const TrackersSettings = (({
currentScreen,
featureStatus,
extensionEnabled,
enableSwitchWasChanged,
extensionSpecialOffers,
specialOffersSwitchWasChanged,
whitelist,
inputWhitelistUrlRef,
whitelistUrlErrorRef,
onClickBack,
addUrlToWhitelist,
deleteUrlFromWhitelist,
bdLang
}) => {
let statusString = bdLang.getString("extension_status_on");
if (!extensionEnabled) {
statusString = bdLang.getString("extension_status_off");
}
let specialOffersString = bdLang.getString("special_offers");
let specialOffersTooltipString = bdLang.getString("special_offers_tooltip");
const displayTrackersWhiteList = () => {
let listItems = [];
if (undefined === whitelist) {
return listItems;
}
for (let i = 0; i < whitelist.length; ++i) {
listItems.push( /*#__PURE__*/react.createElement("li", {
key: i
}, /*#__PURE__*/react.createElement("div", {
className: "url"
}, whitelist[i]), /*#__PURE__*/react.createElement("button", {
className: "remove",
onClick: e => {
deleteUrlFromWhitelist(e, whitelist[i]);
}
})));
}
return listItems;
};
if (currentScreen & SCREEN_UI.SETTINGS) {
return /*#__PURE__*/react.createElement("div", {
className: "whitelist-screen show"
}, /*#__PURE__*/react.createElement("div", null, /*#__PURE__*/react.createElement("button", {
className: "back",
onClick: onClickBack
}), /*#__PURE__*/react.createElement("div", {
className: "page-title"
}, bdLang.getString("settings_title")), /*#__PURE__*/react.createElement("div", {
className: "switch-wrap"
}, /*#__PURE__*/react.createElement("div", null, /*#__PURE__*/react.createElement("div", {
className: "lbl"
}, statusString), /*#__PURE__*/react.createElement("div", {
className: "feat-description"
}, bdLang.getString("extension_status_desc"))), /*#__PURE__*/react.createElement("label", {
className: "switch"
}, /*#__PURE__*/react.createElement("input", {
type: "checkbox",
disabled: !featureStatus,
checked: extensionEnabled,
onChange: enableSwitchWasChanged
}), /*#__PURE__*/react.createElement("div", null))), /*#__PURE__*/react.createElement("div", {
className: "switch-wrap sm"
}, /*#__PURE__*/react.createElement("div", null, /*#__PURE__*/react.createElement("div", {
className: "lbl"
}, specialOffersString), /*#__PURE__*/react.createElement("div", {
className: "tooltip-target"
}, /*#__PURE__*/react.createElement("div", {
className: "info-tooltip"
}, /*#__PURE__*/react.createElement("div", null, specialOffersTooltipString)))), /*#__PURE__*/react.createElement("label", {
className: "switch"
}, /*#__PURE__*/react.createElement("input", {
id: "start_stop_button",
type: "checkbox",
checked: extensionSpecialOffers,
onChange: specialOffersSwitchWasChanged
}), /*#__PURE__*/react.createElement("div", null))), /*#__PURE__*/react.createElement("div", {
className: "section-title"
}, bdLang.getString("exceptions_title")), /*#__PURE__*/react.createElement("div", {
className: "page-description"
}, bdLang.getString("exceptions_desc")), /*#__PURE__*/react.createElement("a", {
onClick: e => {
addUrlToWhitelist(e, true);
}
}, bdLang.getString("add_curr_website")), /*#__PURE__*/react.createElement("br", null), /*#__PURE__*/react.createElement("div", {
className: "added",
hidden: true
}, bdLang.getString("website_added_list")), /*#__PURE__*/react.createElement("div", {
className: "field-label"
}, bdLang.getString("exception_action_desc")), /*#__PURE__*/react.createElement("div", {
className: "field"
}, /*#__PURE__*/react.createElement("div", null, /*#__PURE__*/react.createElement("input", {
type: "text",
className: "text-field",
placeholder: bdLang.getString("website_url_enter"),
ref: inputWhitelistUrlRef
}), /*#__PURE__*/react.createElement("div", {
className: "error-text",
ref: whitelistUrlErrorRef
}, bdLang.getString("url_not_valid"))), /*#__PURE__*/react.createElement("button", {
className: "add",
onClick: e => {
addUrlToWhitelist(e, false);
}
}))), /*#__PURE__*/react.createElement("ul", {
className: "url-list"
}, displayTrackersWhiteList()), /*#__PURE__*/react.createElement("div", {
className: "ad",
hidden: true
}, /*#__PURE__*/react.createElement("div", null, "Try the lastest version of"), /*#__PURE__*/react.createElement("div", {
className: "product-name"
}, "Bitdefender Antivirus Plus"), /*#__PURE__*/react.createElement("button", {
className: "get-free"
}, "Get 3 months free")));
} else {
return null;
}
});
;// CONCATENATED MODULE: ./src/components/StackNavigation.js
/* harmony default export */ const StackNavigation = (({
hostname,
tabStack,
stackIndex,
onStackGoIndex
}) => {
const navigationButtonsTop = 13;
const websiteExtendedWidth = 350;
const websiteReducedWidth = 230;
let stackHasIndex = index => {
return index >= 0 && index <= tabStack.length - 1;
};
let stackCanGoBack = () => {
return stackHasIndex(stackIndex + 1);
};
let stackCanGoForward = () => {
return stackHasIndex(stackIndex - 1);
};
let stackTrackersBlockedAtIndex = index => {
if (stackHasIndex(index)) {
let tabInfo = tabStack[index];
return tabInfo.trackersBlocked;
}
return 0;
};
let stackTrackersBlockedBack = () => {
return stackTrackersBlockedAtIndex(stackIndex + 1);
};
let stackTrackersBlockedForward = () => {
return stackTrackersBlockedAtIndex(stackIndex - 1);
};
let onStackGoBack = () => {
onStackGoIndex(stackIndex + 1);
};
let onStackGoForward = () => {
onStackGoIndex(stackIndex - 1);
};
let stackBackButton = '';
if (stackCanGoBack()) {
let backText = '';
if (stackTrackersBlockedBack() > 0) {
backText = /*#__PURE__*/react.createElement("div", {
className: "backTrackers"
}, stackTrackersBlockedBack());
}
stackBackButton = /*#__PURE__*/react.createElement("label", {
style: {
float: 'left'
}
}, /*#__PURE__*/react.createElement("button", {
id: "stackBack",
className: "back",
style: {
top: navigationButtonsTop
},
onClick: onStackGoBack
}), backText);
}
let stackForwardButton = '';
if (stackCanGoForward()) {
let forwardText = '';
if (stackTrackersBlockedForward() > 0) {
forwardText = /*#__PURE__*/react.createElement("div", {
className: "forwardTrackers"
}, stackTrackersBlockedForward());
}
stackForwardButton = /*#__PURE__*/react.createElement("label", {
style: {
float: 'right'
}
}, forwardText, /*#__PURE__*/react.createElement("button", {
id: "stackForward",
className: "forward",
style: {
top: navigationButtonsTop
},
onClick: onStackGoForward
}));
}
let websiteMaxWidth = websiteExtendedWidth;
if (stackCanGoBack() || stackCanGoForward()) {
websiteMaxWidth = websiteReducedWidth;
}
return /*#__PURE__*/react.createElement("div", {
className: "website-navigation"
}, stackBackButton, /*#__PURE__*/react.createElement("div", {
className: "website",
title: hostname,
style: {
maxWidth: websiteMaxWidth
}
}, hostname), stackForwardButton);
});
// EXTERNAL MODULE: ./node_modules/validator/lib/isURL.js
var isURL = __webpack_require__(492);
var isURL_default = /*#__PURE__*/__webpack_require__.n(isURL);
;// CONCATENATED MODULE: ./src/utils/anims.js
class Pie {
constructor() {
this.canvas = null;
this.tooltip = null;
this.ctx = null;
this.colors = ["#815dc4", "#1cb2a4", "#269ac8", "#b35ca1", "#60aec5", "#e67e17"];
this.x = 0;
this.y = 0;
this.r = 0;
this.lw = 10;
this.angles = [];
this.nrBlockedTrackers = 0;
}
init() {
this.canvas = document.getElementById("pie");
this.tooltip = document.getElementById("pie-tooltip");
this.ctx = this.canvas.getContext("2d");
this.ctx.lineWidth = this.lw;
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.x = this.canvas.width / 2;
this.y = this.x;
this.r = this.x - this.lw / 2 - 0.1;
this.setMouse();
}
clear() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
update(trackers) {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
var totalTrackers = trackers.reduce((a, b) => a + b);
this.nrBlockedTrackers = totalTrackers;
var parts = trackers.length;
var start = 0;
var grad = 0;
document.getElementById("pieCount").firstChild.nodeValue = getTrackerPieCountText(totalTrackers);
for (var i = 0; i < parts; i++) {
this.ctx.beginPath();
this.ctx.strokeStyle = this.colors[i];
grad = Math.PI * 2 * trackers[i] / totalTrackers;
this.ctx.arc(this.x, this.y, this.r, start, start + grad);
this.ctx.stroke();
this.angles.push([start, start + grad, i]);
start += grad;
}
}
mouseEnterEvent() {
this.showTooltip();
}
mouseLeaveEvent() {
this.hideTooltip();
}
mouseMoveEvent(evt) {
var distance = 0;
var angle = 0;
var dx = evt.offsetX - this.x;
var dy = -(evt.offsetY - this.x);
this.tooltip.style.left = evt.offsetX - 40 + "px";
this.tooltip.style.top = evt.offsetY + 10 + "px";
if (0 === this.angles.length) {
return;
}
angle = Math.atan2(dy, dx);
if (angle < 0) {
angle += Math.PI * 2;
}
angle = 2 * Math.PI - angle;
let current = this.angles.filter(function (item) {
if (item[0] <= angle && angle <= item[1]) {
return true;
}
return false;
});
if (null != current && current.length > 0) {
current = current[0][2];
let label = document.querySelectorAll(".tooltip-labels div.show")[0];
if (label) {
label.classList.remove("show");
}
label = document.querySelectorAll(".tooltip-labels div").item(current);
label.classList.add("show");
distance = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
if (distance < this.x - this.lw || distance > this.x + this.lw) {
this.hideTooltip();
} else {
this.showTooltip();
}
}
}
setMouse() {
this.canvas.addEventListener("mouseenter", this.mouseEnterEvent.bind(this));
this.canvas.addEventListener("mouseleave", this.mouseLeaveEvent.bind(this));
this.canvas.addEventListener("mousemove", this.mouseMoveEvent.bind(this));
}
hideTooltip() {
this.tooltip.style.display = "none";
}
showTooltip() {
if (this.nrBlockedTrackers > 0) {
this.tooltip.style.display = "block";
}
}
}
;
class PageLoad {
constructor() {
this.canvas = null;
this.ctx = null;
this.lw = 8;
this.x = 0;
this.y = 0;
this.r = 0;
}
init() {
this.canvas = document.getElementById("pageSpeed");
this.ctx = this.canvas.getContext("2d");
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.x = this.canvas.width / 2;
this.r = this.x - this.lw / 2 - 0.1;
}
clear() {
indicator.style.transform = "rotate(0deg)";
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
update(val) {
var gradient;
var grad;
var offset = 0.08;
var start = Math.PI;
var rotation = val / 100 * 182 - 91;
var indicator = document.getElementById("indicator");
indicator.style.transform = "rotate(" + rotation + "deg)";
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.beginPath();
this.ctx.lineWidth = this.lw;
grad = Math.PI * 2 * val / 100.0 / 2 - start;
if (val < 35) {
gradient = this.ctx.createLinearGradient(0, 40, 20, 0);
gradient.addColorStop(0, "#d90016");
gradient.addColorStop(1, "#e15765");
this.ctx.strokeStyle = gradient;
} else if (val >= 35 && val < 55) {
gradient = this.ctx.createLinearGradient(0, 40, 50, 0);
gradient.addColorStop(0, "#ff9933");
gradient.addColorStop(1, "#f7d360");
this.ctx.strokeStyle = gradient;
} else {
gradient = this.ctx.createLinearGradient(0, 40, 80, 40);
gradient.addColorStop(0, "#1f991f");
gradient.addColorStop(1, "#42c942");
this.ctx.strokeStyle = gradient;
}
this.ctx.arc(this.x, this.x, this.r, start - offset, grad);
this.ctx.stroke();
this.ctx.beginPath();
this.ctx.strokeStyle = "#cccccc";
this.ctx.arc(this.x, this.x, this.r, grad, 0 + offset);
this.ctx.stroke();
}
}
;
class PageTooltip {
constructor() {}
init() {
var targets = document.querySelectorAll(".tooltip-target");
targets.forEach(function (elem) {
var tooltip = elem.querySelector(".info-tooltip");
if (null != tooltip) {
elem.addEventListener("mouseover", function () {
var br = elem.getBoundingClientRect();
if (br.left > 240) {
tooltip.classList.add("left");
} else {
tooltip.classList.remove("left");
}
});
}
});
}
}
;
;// CONCATENATED MODULE: ./src/localization/locale_lang.js
/**
* get lang Map
* @param {*} langJson
*/
function getLangMap(langJson) {
let langMap = new Map();
let keys = Object.keys(langJson);
for (let index = 0; index < keys.length; index++) {
let key = keys[index];
if (null != key) {
langMap.set(key, langJson[key]["message"]);
}
}
return langMap;
}
function extensionLangFromProductLang(productLang) {
let extensionLang = productLang;
if (!extensionLang.startsWith('pt')) {
extensionLang = extensionLang.substring(0, 2);
} else {
extensionLang = extensionLang.replace("-", "_");
}
return extensionLang;
}
class BdLang {
constructor() {
this.langMap = null;
}
init(_langMap) {
this.langMap = _langMap;
}
getString(message) {
if (null != this.langMap) {
if (this.langMap.has(message)) {
return this.langMap.get(message);
}
}
return chrome.i18n.getMessage(message);
}
}
/* harmony default export */ const locale_lang = (new BdLang());
;// CONCATENATED MODULE: ./src/ui/home.js
class Home extends react.Component {
constructor(props) {
super(props);
this.state = {
tabId: props.currentTab.id,
hostname: utils_parseUrl(props.currentTab.url).hostname,
featureStatus: props.featureStatus,
enabled: props.enabled,
categories: props.categories,
specialOffers: props.specialOffers,
stackIndex: 0,
tabStack: [],
pageLoad: 0,
trackersBlocked: 0,
trackersMap: {},
trackersUrls: [],
whitelist: props.whitelist,
isUpdate: false
};
this.currentScreen = SCREEN_UI.MAIN;
this.pie = new Pie();
this.pageLoad = new PageLoad();
this.pageTooltip = new PageTooltip();
this.sessionWhitelist = [];
this.categoryKey = 0;
this.featureStatus = this.state.featureStatus;
this.extensionEnabled = this.state.enabled;
this.extensionSpecialOffers = this.state.specialOffers;
this.inputWhitelistUrlRef = /*#__PURE__*/react.createRef();
this.whitelistUrlErrorRef = /*#__PURE__*/react.createRef();
this.categoryExpandRef = /*#__PURE__*/react.createRef();
this.dnrBadgeMessage = '';
log.init('popup');
if (props.rulesMatchedDetails) {
this.onDnrMatchedRules(props.rulesMatchedDetails);
}
chrome.runtime.onMessage.addListener(this.onBackgroundMessage);
chrome.runtime.sendMessage({
type: 'get_current_tab_stack',
tabId: this.props.currentTab.id,
tabUrl: props.currentTab.url
}, response => {
if (response) {
this.sessionWhitelist = response.sessionWhitelist;
if (undefined !== response.langMap && null != response.langMap) {
locale_lang.init(new Map(JSON.parse(response.langMap)));
}
let tabInfo = response.tabStack[0];
if (canBlockWebRequest()) {
this.setState({
hostname: tabInfo.url,
stackIndex: 0,
tabStack: response.tabStack,
pageLoad: tabInfo.pageLoad,
trackersBlocked: tabInfo.trackersBlocked,
trackersMap: tabInfo.trackersMap,
trackersUrls: tabInfo.trackersUrls,
isUpdate: tabInfo.isUpdate
});
} else {
this.setState({
pageLoad: tabInfo.pageLoad,
trackersUrls: tabInfo.trackersUrls,
isUpdate: tabInfo.isUpdate
});
}
}
});
log.trace('ctor');
}
componentDidMount() {
log.trace('componentDidMount');
if (null != this.pie) {
this.pie.init();
}
if (null != this.pageLoad) {
this.pageLoad.init();
}
if (null != this.pageTooltip) {
this.pageTooltip.init();
}
}
componentDidUpdate() {
log.trace('componentDidUpdate');
if (this.state.trackersBlocked === 0) {
if (null != this.pie) {
this.pie.clear();
}
}
if (this.state.pageLoad === 0) {
if (null != this.pageLoad) {
this.pageLoad.clear();
}
}
}
getProtectionStatusClassName = () => {
if (this.extensionEnabled) {
if (undefined !== this.sessionWhitelist && this.sessionWhitelist.includes(this.state.hostname)) {
return 'main-screen disabled-protection';
} else {
return 'main-screen';
}
} else {
return 'main-screen disabled-shadow';
}
};
trackersMapIsEmpty = () => {
if (undefined === this.state.trackersMap || 0 === this.state.trackersMap.size) {
return true;
}
if (0 === Object.keys(this.state.trackersMap).length) {
return true;
}
return false;
};
updatePageLoad = () => {
if (null != this.pageLoad && this.state.pageLoad > 0) {
if (this.state.pageLoad <= 1) {
this.pageLoad.update(100); // val 0 - 100
} else if (this.state.pageLoad <= 2) {
this.pageLoad.update(90);
} else if (this.state.pageLoad <= 3) {
this.pageLoad.update(70);
} else if (this.state.pageLoad <= 4) {
this.pageLoad.update(50);
} else if (this.state.pageLoad <= 5) {
this.pageLoad.update(40);
} else if (this.state.pageLoad <= 6) {
this.pageLoad.update(30);
} else if (this.state.pageLoad <= 7) {
this.pageLoad.update(20);
} else if (this.state.pageLoad <= 8) {
this.pageLoad.update(10);
} else if (this.state.pageLoad <= 9) {
this.pageLoad.update(5);
} else if (this.state.pageLoad <= 10) {
this.pageLoad.update(2.5);
} else {
this.pageLoad.update(0);
}
}
};
updatePieTooltips = () => {
this.updatePageLoad();
if (!this.trackersMapIsEmpty()) {
let categoriesNrTrackers = [0, 0, 0, 0, 0, 0];
const keys = Object.keys(this.state.trackersMap);
for (const key of keys) {
let index = -1;
switch (key) {
case '1':
//ads
{
index = 0;
break;
}
case '2':
//analytics
{
index = 3;
break;
}
case '4':
//customer interaction
{
index = 1;
break;
}
case '8':
//social media
{
index = 4;
break;
}
case '16':
//essentials
{
index = 2;
break;
}
case '32':
//cookies
{
index = 5;
break;
}
}
if (-1 != index) {
categoriesNrTrackers[index] = this.state.trackersMap[key].length;
}
}
if (null != this.pie) {
this.pie.update(categoriesNrTrackers);
}
}
return null;
};
onCategoryListItemClick = event => {
this.categoryKey = event.currentTarget.dataset.id;
this.currentScreen = SCREEN_UI.CATEGORY;
this.setState({
state: this.state
});
};
onClickSettings = event => {
this.currentScreen = SCREEN_UI.SETTINGS;
this.setState({
state: this.state
});
};
onClickBack = () => {
this.currentScreen = SCREEN_UI.MAIN;
this.setState({
state: this.state
});
};
onClickCategoryLink = () => {
if ('dashboard expand' === this.categoryExpandRef.current.className) {
this.categoryExpandRef.current.className = 'dashboard';
} else {
this.categoryExpandRef.current.className = 'dashboard expand';
}
};
showTrackersList = () => {
let listItems = [];
const keys = ['1', '2', '4', '8', '16', '32'];
for (const key of keys) {
let categoryInfo = getTrackerCategoryName(locale_lang, key);
let nrTracks = 0;
if (undefined !== this.state.trackersMap && 0 !== Object.keys(this.state.trackersMap).length) {
if (null != this.state.trackersMap[key]) {
nrTracks = this.state.trackersMap[key].length;
}
}
let nrTrackersBlocked = nrTracks + ' ' + locale_lang.getString("str");
listItems.push( /*#__PURE__*/react.createElement("li", {
className: categoryInfo.icon,
key: key,
"data-id": key,
onClick: this.onCategoryListItemClick
}, /*#__PURE__*/react.createElement("div", {
className: "title with-tooltip"
}, /*#__PURE__*/react.createElement("span", null, categoryInfo.name), /*#__PURE__*/react.createElement("div", {
className: "tooltip-target"
}, /*#__PURE__*/react.createElement("div", {
className: "info-tooltip up"
}, /*#__PURE__*/react.createElement("div", null, getTrackerCategoryTooltip(locale_lang, key))))), /*#__PURE__*/react.createElement("div", {
className: "trackers"
}, nrTrackersBlocked)));
}
return listItems;
};
enableSwitchWasChanged = () => {
this.extensionEnabled = !this.state.enabled;
this.setState(prevState => ({
enabled: !prevState.enabled
}), this.stateWasUpdatedFromUI);
};
specialOffersSwitchWasChanged = () => {
this.extensionSpecialOffers = !this.state.specialOffers;
this.setState({
specialOffers: this.extensionSpecialOffers
}, () => {
chrome.storage.local.set(this.state);
chrome.runtime.sendMessage({
type: 'special_offers',
specialOffers: this.state.specialOffers
});
});
};
categoryStatusChanged = event => {
log.info('categoryStatusChanged: ' + event.target.checked);
let newCategories = 0;
if (true === event.target.checked) {
newCategories = this.state.categories & ~this.categoryKey;
} else {
newCategories = this.state.categories | this.categoryKey;
}
this.setState({
categories: newCategories
}, this.stateWasUpdatedFromUI);
log.info("categories: " + newCategories);
};
addUrlToWhitelist = (event, isCurrentUrl) => {
log.info('addWhiteListUrl: ' + isCurrentUrl);
const textFieldError = 'text-field error';
let whitelistUrl = null;
if (isCurrentUrl) {
whitelistUrl = this.state.hostname;
} else {
whitelistUrl = this.inputWhitelistUrlRef.current.value;
}
log.info('url: ' + whitelistUrl);
if (null === whitelistUrl || 0 === whitelistUrl.length) {
this.whitelistUrlErrorRef.current.textContent = locale_lang.getString('url_is_empty');
this.inputWhitelistUrlRef.current.className = textFieldError;
return;
}
let currentUrl = whitelistUrl;
if (!/^https?:/i.test(whitelistUrl)) {
currentUrl = 'https://' + whitelistUrl;
}
if (!isURL_default()(currentUrl)) {
this.whitelistUrlErrorRef.current.textContent = locale_lang.getString('url_not_valid');
this.inputWhitelistUrlRef.current.className = textFieldError;
return;
}
whitelistUrl = utils_parseUrl(currentUrl).hostname;
log.info("url: " + currentUrl);
log.info("whitelistUrl: " + whitelistUrl);
if (whitelistUrl.startsWith("www.")) {
whitelistUrl = whitelistUrl.substring(4);
}
let reg = new RegExp('[\.]([^$.?#]+)');
if (!reg.test(whitelistUrl)) {
this.whitelistUrlErrorRef.current.textContent = locale_lang.getString('url_not_valid');
this.inputWhitelistUrlRef.current.className = textFieldError;
return;
}
if (this.state.whitelist.includes(whitelistUrl)) {
this.whitelistUrlErrorRef.current.textContent = locale_lang.getString('url_already_exists');
this.inputWhitelistUrlRef.current.className = textFieldError;
return;
}
this.setState({
whitelist: this.state.whitelist.concat(whitelistUrl)
}, () => {
chrome.storage.local.set(this.state);
chrome.runtime.sendMessage({
type: 'whitelist_changed',
whitelist: this.state.whitelist,
whitelist_add: whitelistUrl
});
log.info('whitelist (add):' + this.state.whitelist);
});
this.inputWhitelistUrlRef.current.value = '';
this.inputWhitelistUrlRef.current.className = 'text-field';
};
deleteUrlFromWhitelist = (event, url) => {
log.info('deleteUrlFromWhitelist: ' + url);
if (null === url || 0 === url.length) {
return;
}
this.setState({
whitelist: this.state.whitelist.filter(site => site !== url)
}, () => {
chrome.storage.local.set(this.state);
chrome.runtime.sendMessage({
type: 'whitelist_changed',
whitelist: this.state.whitelist,
whitelist_remove: url
});
log.info('whitelist (delete):' + this.state.whitelist);
});
};
siteWasDisabled = () => {
log.info('siteWasDisabled');
if (!this.sessionWhitelist.includes(this.state.hostname)) {
this.sessionWhitelist = this.sessionWhitelist.concat(this.state.hostname);
}
chrome.runtime.sendMessage({
type: 'sessionWhitelist_changed',
sessionWhitelist: this.sessionWhitelist,
disabled: true,
url: this.state.hostname
});
this.setState({
state: this.state.enabled
});
};
siteWasEnabled = () => {
log.info('siteWasEnabled');
this.sessionWhitelist = this.sessionWhitelist.filter(site => site !== this.state.hostname);
chrome.runtime.sendMessage({
type: 'sessionWhitelist_changed',
sessionWhitelist: this.sessionWhitelist,
disabled: false
});
this.setState({
state: this.state.enabled
});
};
/**
* Sync every UI state change with local storage and background process.
*/
stateWasUpdatedFromUI = () => {
chrome.storage.local.set(this.state);
chrome.runtime.sendMessage({
type: 'new_state',
state: this.state
});
};
dnrUpdateMatchedRules = () => {
if (scripts_compat.dnr.available) {
getBadgeMessage(this.props.currentTab.id, text => {
if (text !== this.dnrBadgeMessage) {
this.dnrBadgeMessage = text;
log.warn('[dnr] v3 query dnr rule matching data for new stats: ' + this.dnrBadgeMessage);
scripts_compat.dnr.declarativeNetRequest.getMatchedRules({
tabId: this.props.currentTab.id
}, this.onDnrMatchedRules.bind(this));
} else {
log.warn('[dnr] v3 skip dnr rule matching query due to same badge action count');
}
});
}
};
onDnrMatchedRules = rulesMatchedDetails => {
if (!rulesMatchedDetails) {
return;
}
log.warn('[dnr] onDnrMatchedRules: ' + JSON.stringify(rulesMatchedDetails, null, 4));
if (!canBlockWebRequest()) {
if (rulesMatchedDetails.rulesMatchedInfo.length > 0) {
const trackersUrl = chrome.runtime.getURL('tracking/trackers.json');
fetch(trackersUrl).then(response => response.json()) //assuming file contains json
.then(json => {
let trackersBlocked = 0;
let trackersMap = {};
trackersMap[(tracking_default()).categories.ADS] = [];
trackersMap[(tracking_default()).categories.SITE_ANALYTICS] = [];
trackersMap[(tracking_default()).categories.CUSTOMER_INTERACTION] = [];
trackersMap[(tracking_default()).categories.SOCIAL_MEDIA] = [];
trackersMap[(tracking_default()).categories.ESSENTIAL] = [];
trackersMap[(tracking_default()).categories.COOKIE] = [];
let domainCookies = tracking_default().getDomainCookies();
rulesMatchedDetails.rulesMatchedInfo.forEach(match => {
if (match.tabId !== this.state.tabId) {
return;
}
let rule = match.rule;
if (json.hasOwnProperty(rule.rulesetId)) {
let rulesetTrackers = json[rule.rulesetId];
let rulesetInnerId = rule.ruleId % 10000;
if (rulesetInnerId > 0 && rulesetTrackers.length > rulesetInnerId) {
let ruleExpr = rulesetTrackers[rulesetInnerId - 1];
log.warn('[dnr] onDnrMatchedRules match: ' + '[' + rule.rulesetId + '][' + rulesetInnerId + '][' + ruleExpr + ']' + JSON.stringify(rule, null, 4));
let rulesetCategId = tracking_default().categoryStringToId(rule.rulesetId);
if (rulesetCategId != (tracking_default()).categories.UNKNOWN) {
trackersBlocked++;
trackersMap[rulesetCategId].push(ruleExpr);
}
}
} else {
if (rule.rulesetId === (tracking_default()).rulesets.domain_cookies) {
let rulesetInnerId = rule.ruleId % 10000;
if (rulesetInnerId > 0 && domainCookies.length > rulesetInnerId) {
let ruleDomain = domainCookies[rulesetInnerId - 1];
log.warn('[dnr] onDnrMatchedRules match: ' + '[' + rule.rulesetId + '][' + rulesetInnerId + '][' + ruleDomain + ']' + JSON.stringify(rule, null, 4));
trackersBlocked++;
trackersMap[(tracking_default()).categories.COOKIE].push(ruleDomain);
}
}
}
});
log.warn('[dnr] onDnrMatchedRules trackersMap: ' + JSON.stringify(trackersMap, null, 4));
if (trackersBlocked > 0) {
let newState = {
trackersBlocked: trackersBlocked,
trackersMap: trackersMap
};
getBadgeMessage(this.props.currentTab.id, text => {
if (text !== this.dnrBadgeMessage) {
this.dnrBadgeMessage = text;
log.warn('[dnr] v3 update dnr rule matching data with new stats: ' + this.dnrBadgeMessage);
}
});
log.warn('[dnr] onDnrMatchedRules newState: ' + JSON.stringify(newState, null, 4));
this.setState(newState);
}
});
}
}
};
/**
* Receive messages from background process and update UI.
*/
onBackgroundMessage = (request, sender, sendResponse) => {
log.info('onBackgroundMessage: ' + request.type);
switch (request.type) {
case 'update_tab_stack':
{
this.sessionWhitelist = request.sessionWhitelist;
if (undefined !== request.tabStack) {
let tabInfo = request.tabStack[0];
if (undefined !== tabInfo) {
this.setState({
hostname: tabInfo.url,
stackIndex: 0,
tabStack: request.tabStack,
pageLoad: tabInfo.pageLoad,
trackersBlocked: tabInfo.trackersBlocked,
trackersMap: tabInfo.trackersMap,
trackersUrls: tabInfo.trackersUrls
});
}
}
break;
}
case 'update_page_load':
{
if (undefined !== request.tabStack) {
let tabInfo = request.tabStack[0];
if (undefined !== tabInfo) {
this.setState({
pageLoad: tabInfo.pageLoad
}, () => {
this.dnrUpdateMatchedRules();
});
}
}
break;
}
case 'new_state':
{
this.extensionEnabled = request.state;
this.setState({
enabled: request.state
});
break;
}
case 'set_settings':
{
this.extensionEnabled = request.enabled;
this.setState({
featureStatus: request.featureStatus,
enabled: request.enabled,
categories: request.categories
});
break;
}
case 'set_module_status':
{
this.extensionEnabled = request.enabled;
this.setState({
featureStatus: request.featureStatus,
enabled: request.enabled
});
break;
}
case 'whitelist_add':
{
let url = request.url;
if (!this.state.whitelist.includes(url)) {
log.info('add url to whitelist: ' + url);
this.setState({
whitelist: this.state.whitelist.concat(url)
});
}
break;
}
case 'whitelist_remove':
{
let url = request.url;
if (this.state.whitelist.includes(url)) {
log.info('remove url from whitelist: ' + url);
this.setState({
whitelist: this.state.whitelist.filter(site => site !== url)
});
}
break;
}
case 'set_whitelist':
{
let whitelist = request.whitelist;
if (Array.isArray(whitelist)) {
log.info('set new whitelist: ' + whitelist);
this.setState({
whitelist: whitelist.slice(0)
});
}
break;
}
default:
{
break;
}
}
};
onStackGoIndex = index => {
if (index >= 0 && index <= this.state.tabStack.length - 1) {
let tabInfo = this.state.tabStack[index];
this.setState({
hostname: tabInfo.url,
stackIndex: index,
pageLoad: tabInfo.pageLoad,
trackersBlocked: tabInfo.trackersBlocked,
trackersMap: tabInfo.trackersMap,
trackersUrls: tabInfo.trackersUrls
});
}
};
render() {
if (this.state.isUpdate) {
return /*#__PURE__*/react.createElement("div", {
className: "main-ui"
}, /*#__PURE__*/react.createElement("header", null, /*#__PURE__*/react.createElement("div", {
className: "title"
}, locale_lang.getString("app_name"))), /*#__PURE__*/react.createElement("div", {
className: "center"
}, /*#__PURE__*/react.createElement("h2", null, locale_lang.getString("update_in_progress"))));
}
return /*#__PURE__*/react.createElement("div", {
className: "main-ui"
}, /*#__PURE__*/react.createElement("header", null, /*#__PURE__*/react.createElement("div", {
className: "title"
}, locale_lang.getString("app_name")), /*#__PURE__*/react.createElement(DebuggingUtils_Home, null), /*#__PURE__*/react.createElement("button", {
className: "settings",
onClick: this.onClickSettings
})), /*#__PURE__*/react.createElement("div", {
className: this.getProtectionStatusClassName()
}, /*#__PURE__*/react.createElement("div", {
className: "dashboard"
}, /*#__PURE__*/react.createElement("div", {
className: "total-trackers",
hidden: true
}, /*#__PURE__*/react.createElement("strong", null, "252"), " ", /*#__PURE__*/react.createElement("span", null, locale_lang.getString("browser_session_blocked"))), /*#__PURE__*/react.createElement(StackNavigation, {
hostname: this.state.hostname,
tabStack: this.state.tabStack,
stackIndex: this.state.stackIndex,
onStackGoIndex: this.onStackGoIndex
}), /*#__PURE__*/react.createElement("div", {
className: "gauges-container"
}, /*#__PURE__*/react.createElement("div", {
className: "pie-wprap"
}, /*#__PURE__*/react.createElement("canvas", {
className: "trackers-pie",
id: "pie",
width: "110",
height: "110"
}), /*#__PURE__*/react.createElement("div", {
className: "count",
id: "pieCount"
}, getTrackerPieCountText(this.state.trackersBlocked)), /*#__PURE__*/react.createElement("div", {
className: "label"
}, locale_lang.getString("trackers_blocked")), /*#__PURE__*/react.createElement("div", {
className: "info-tooltip",
id: "pie-tooltip"
}, /*#__PURE__*/react.createElement("div", {
className: "tooltip-labels"
}, this.updatePieTooltips(), /*#__PURE__*/react.createElement("div", null, locale_lang.getString("advertising_trackers_tooltip")), /*#__PURE__*/react.createElement("div", null, locale_lang.getString("interaction_trackers_tooltip")), /*#__PURE__*/react.createElement("div", null, locale_lang.getString("essentials_trackers_tooltip")), /*#__PURE__*/react.createElement("div", null, locale_lang.getString("analytics_trackers_tooltip")), /*#__PURE__*/react.createElement("div", null, locale_lang.getString("social_trackers_tooltip")), /*#__PURE__*/react.createElement("div", null, locale_lang.getString("cookies_trackers_tooltip"))))), /*#__PURE__*/react.createElement("div", null, /*#__PURE__*/react.createElement("div", {
className: "load-gauge"
}, /*#__PURE__*/react.createElement("canvas", {
id: "pageSpeed",
width: "88",
height: "88"
}), /*#__PURE__*/react.createElement("div", {
className: "indicator",
id: "indicator"
}), /*#__PURE__*/react.createElement("div", {
className: "speed"
}, /*#__PURE__*/react.createElement("span", null, this.state.pageLoad), /*#__PURE__*/react.createElement("span", null, locale_lang.getString("seconds")))), /*#__PURE__*/react.createElement("div", {
className: "label"
}, locale_lang.getString("page_load")))), /*#__PURE__*/react.createElement(DisableButton, {
sessionWhitelist: this.sessionWhitelist,
currentUrl: this.state.hostname,
onSiteDisable: this.siteWasDisabled,
onSiteEnable: this.siteWasEnabled,
bdLang: locale_lang
})), /*#__PURE__*/react.createElement("ul", {
className: "trackers-list"
}, this.showTrackersList())), /*#__PURE__*/react.createElement(TrackersCategory, {
currentScreen: this.currentScreen,
currentCategoryKey: this.categoryKey,
categoryExpandRef: this.categoryExpandRef,
categories: this.state.categories,
trackersMap: this.state.trackersMap,
trackersUrls: this.state.trackersUrls,
categoryStatusChanged: this.categoryStatusChanged,
onClickCategoryLink: this.onClickCategoryLink,
onClickBack: this.onClickBack,
bdLang: locale_lang
}), /*#__PURE__*/react.createElement(TrackersSettings, {
currentScreen: this.currentScreen,
featureStatus: this.featureStatus,
extensionEnabled: this.extensionEnabled,
enableSwitchWasChanged: this.enableSwitchWasChanged,
extensionSpecialOffers: this.extensionSpecialOffers,
specialOffersSwitchWasChanged: this.specialOffersSwitchWasChanged,
whitelist: this.state.whitelist,
inputWhitelistUrlRef: this.inputWhitelistUrlRef,
whitelistUrlErrorRef: this.whitelistUrlErrorRef,
onClickBack: this.onClickBack,
addUrlToWhitelist: this.addUrlToWhitelist,
deleteUrlFromWhitelist: this.deleteUrlFromWhitelist,
bdLang: locale_lang
}));
}
}
// EXTERNAL MODULE: ./node_modules/react-dom/client.js
var client = __webpack_require__(745);
;// CONCATENATED MODULE: ./src/storage/defaults.js
let defaultState = {
featureStatus: true,
enabled: true,
specialOffers: true,
categories: 127,
globalBlocked: 0,
whitelist: [],
mustSyncWhitelist: false,
acceptedAppPolicy: false
};
function loadAndInitStoredState(callback) {
chrome.storage.local.get(storedState => {
let initialState = {
...defaultState,
...storedState
};
if (storedState) {
if (storedState.whitelist && storedState.whitelist.length > 0) {
if (!storedState.hasOwnProperty('mustSyncWhitelist')) {
initialState.mustSyncWhitelist = true;
}
}
if (!storedState.hasOwnProperty('acceptedAppPolicy')) {
initialState.acceptedAppPolicy = false;
}
}
callback(initialState);
});
}
;// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var tslib_es6_assign = function() {
tslib_es6_assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return tslib_es6_assign.apply(this, arguments);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
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;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __createBinding(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}
function __exportStar(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function tslib_es6_spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
;// CONCATENATED MODULE: ./node_modules/@sentry/utils/esm/is.js
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/**
* Checks whether given value's type is one of a few Error or Error-like
* {@link isError}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isError(wat) {
switch (Object.prototype.toString.call(wat)) {
case '[object Error]':
return true;
case '[object Exception]':
return true;
case '[object DOMException]':
return true;
default:
return isInstanceOf(wat, Error);
}
}
/**
* Checks whether given value's type is ErrorEvent
* {@link isErrorEvent}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isErrorEvent(wat) {
return Object.prototype.toString.call(wat) === '[object ErrorEvent]';
}
/**
* Checks whether given value's type is DOMError
* {@link isDOMError}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isDOMError(wat) {
return Object.prototype.toString.call(wat) === '[object DOMError]';
}
/**
* Checks whether given value's type is DOMException
* {@link isDOMException}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isDOMException(wat) {
return Object.prototype.toString.call(wat) === '[object DOMException]';
}
/**
* Checks whether given value's type is a string
* {@link isString}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isString(wat) {
return Object.prototype.toString.call(wat) === '[object String]';
}
/**
* Checks whether given value's is a primitive (undefined, null, number, boolean, string, bigint, symbol)
* {@link isPrimitive}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isPrimitive(wat) {
return wat === null || (typeof wat !== 'object' && typeof wat !== 'function');
}
/**
* Checks whether given value's type is an object literal
* {@link isPlainObject}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isPlainObject(wat) {
return Object.prototype.toString.call(wat) === '[object Object]';
}
/**
* Checks whether given value's type is an Event instance
* {@link isEvent}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isEvent(wat) {
return typeof Event !== 'undefined' && isInstanceOf(wat, Event);
}
/**
* Checks whether given value's type is an Element instance
* {@link isElement}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isElement(wat) {
return typeof Element !== 'undefined' && isInstanceOf(wat, Element);
}
/**
* Checks whether given value's type is an regexp
* {@link isRegExp}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isRegExp(wat) {
return Object.prototype.toString.call(wat) === '[object RegExp]';
}
/**
* Checks whether given value has a then function.
* @param wat A value to be checked.
*/
function isThenable(wat) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return Boolean(wat && wat.then && typeof wat.then === 'function');
}
/**
* Checks whether given value's type is a SyntheticEvent
* {@link isSyntheticEvent}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
function isSyntheticEvent(wat) {
return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;
}
/**
* Checks whether given value's type is an instance of provided constructor.
* {@link isInstanceOf}.
*
* @param wat A value to be checked.
* @param base A constructor to be used in a check.
* @returns A boolean representing the result.
*/
function isInstanceOf(wat, base) {
try {
return wat instanceof base;
}
catch (_e) {
return false;
}
}
//# sourceMappingURL=is.js.map
// EXTERNAL MODULE: ./node_modules/@sentry/utils/esm/time.js
var time = __webpack_require__(170);
;// CONCATENATED MODULE: ./node_modules/@sentry/utils/esm/syncpromise.js
/* eslint-disable @typescript-eslint/explicit-function-return-type */
/* eslint-disable @typescript-eslint/typedef */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/* eslint-disable @typescript-eslint/no-explicit-any */
/** SyncPromise internal states */
var States;
(function (States) {
/** Pending */
States["PENDING"] = "PENDING";
/** Resolved / OK */
States["RESOLVED"] = "RESOLVED";
/** Rejected / Error */
States["REJECTED"] = "REJECTED";
})(States || (States = {}));
/**
* Thenable class that behaves like a Promise and follows it's interface
* but is not async internally
*/
var syncpromise_SyncPromise = /** @class */ (function () {
function SyncPromise(executor) {
var _this = this;
this._state = States.PENDING;
this._handlers = [];
/** JSDoc */
this._resolve = function (value) {
_this._setResult(States.RESOLVED, value);
};
/** JSDoc */
this._reject = function (reason) {
_this._setResult(States.REJECTED, reason);
};
/** JSDoc */
this._setResult = function (state, value) {
if (_this._state !== States.PENDING) {
return;
}
if (isThenable(value)) {
value.then(_this._resolve, _this._reject);
return;
}
_this._state = state;
_this._value = value;
_this._executeHandlers();
};
// TODO: FIXME
/** JSDoc */
this._attachHandler = function (handler) {
_this._handlers = _this._handlers.concat(handler);
_this._executeHandlers();
};
/** JSDoc */
this._executeHandlers = function () {
if (_this._state === States.PENDING) {
return;
}
var cachedHandlers = _this._handlers.slice();
_this._handlers = [];
cachedHandlers.forEach(function (handler) {
if (handler.done) {
return;
}
if (_this._state === States.RESOLVED) {
if (handler.onfulfilled) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
handler.onfulfilled(_this._value);
}
}
if (_this._state === States.REJECTED) {
if (handler.onrejected) {
handler.onrejected(_this._value);
}
}
handler.done = true;
});
};
try {
executor(this._resolve, this._reject);
}
catch (e) {
this._reject(e);
}
}
/** JSDoc */
SyncPromise.resolve = function (value) {
return new SyncPromise(function (resolve) {
resolve(value);
});
};
/** JSDoc */
SyncPromise.reject = function (reason) {
return new SyncPromise(function (_, reject) {
reject(reason);
});
};
/** JSDoc */
SyncPromise.all = function (collection) {
return new SyncPromise(function (resolve, reject) {
if (!Array.isArray(collection)) {
reject(new TypeError("Promise.all requires an array as input."));
return;
}
if (collection.length === 0) {
resolve([]);
return;
}
var counter = collection.length;
var resolvedCollection = [];
collection.forEach(function (item, index) {
SyncPromise.resolve(item)
.then(function (value) {
resolvedCollection[index] = value;
counter -= 1;
if (counter !== 0) {
return;
}
resolve(resolvedCollection);
})
.then(null, reject);
});
});
};
/** JSDoc */
SyncPromise.prototype.then = function (onfulfilled, onrejected) {
var _this = this;
return new SyncPromise(function (resolve, reject) {
_this._attachHandler({
done: false,
onfulfilled: function (result) {
if (!onfulfilled) {
// TODO: ¯\_(ツ)_/¯
// TODO: FIXME
resolve(result);
return;
}
try {
resolve(onfulfilled(result));
return;
}
catch (e) {
reject(e);
return;
}
},
onrejected: function (reason) {
if (!onrejected) {
reject(reason);
return;
}
try {
resolve(onrejected(reason));
return;
}
catch (e) {
reject(e);
return;
}
},
});
});
};
/** JSDoc */
SyncPromise.prototype.catch = function (onrejected) {
return this.then(function (val) { return val; }, onrejected);
};
/** JSDoc */
SyncPromise.prototype.finally = function (onfinally) {
var _this = this;
return new SyncPromise(function (resolve, reject) {
var val;
var isRejected;
return _this.then(function (value) {
isRejected = false;
val = value;
if (onfinally) {
onfinally();
}
}, function (reason) {
isRejected = true;
val = reason;
if (onfinally) {
onfinally();
}
}).then(function () {
if (isRejected) {
reject(val);
return;
}
resolve(val);
});
});
};
/** JSDoc */
SyncPromise.prototype.toString = function () {
return '[object SyncPromise]';
};
return SyncPromise;
}());
//# sourceMappingURL=syncpromise.js.map
// EXTERNAL MODULE: ./node_modules/@sentry/utils/esm/misc.js
var misc = __webpack_require__(844);
;// CONCATENATED MODULE: ./node_modules/@sentry/hub/esm/scope.js
/**
* Holds additional event information. {@link Scope.applyToEvent} will be
* called by the client before an event will be sent.
*/
var Scope = /** @class */ (function () {
function Scope() {
/** Flag if notifiying is happening. */
this._notifyingListeners = false;
/** Callback for client to receive scope changes. */
this._scopeListeners = [];
/** Callback list that will be called after {@link applyToEvent}. */
this._eventProcessors = [];
/** Array of breadcrumbs. */
this._breadcrumbs = [];
/** User */
this._user = {};
/** Tags */
this._tags = {};
/** Extra */
this._extra = {};
/** Contexts */
this._contexts = {};
}
/**
* Inherit values from the parent scope.
* @param scope to clone.
*/
Scope.clone = function (scope) {
var newScope = new Scope();
if (scope) {
newScope._breadcrumbs = tslib_es6_spread(scope._breadcrumbs);
newScope._tags = tslib_es6_assign({}, scope._tags);
newScope._extra = tslib_es6_assign({}, scope._extra);
newScope._contexts = tslib_es6_assign({}, scope._contexts);
newScope._user = scope._user;
newScope._level = scope._level;
newScope._span = scope._span;
newScope._session = scope._session;
newScope._transactionName = scope._transactionName;
newScope._fingerprint = scope._fingerprint;
newScope._eventProcessors = tslib_es6_spread(scope._eventProcessors);
}
return newScope;
};
/**
* Add internal on change listener. Used for sub SDKs that need to store the scope.
* @hidden
*/
Scope.prototype.addScopeListener = function (callback) {
this._scopeListeners.push(callback);
};
/**
* @inheritDoc
*/
Scope.prototype.addEventProcessor = function (callback) {
this._eventProcessors.push(callback);
return this;
};
/**
* @inheritDoc
*/
Scope.prototype.setUser = function (user) {
this._user = user || {};
if (this._session) {
this._session.update({ user: user });
}
this._notifyScopeListeners();
return this;
};
/**
* @inheritDoc
*/
Scope.prototype.getUser = function () {
return this._user;
};
/**
* @inheritDoc
*/
Scope.prototype.setTags = function (tags) {
this._tags = tslib_es6_assign(tslib_es6_assign({}, this._tags), tags);
this._notifyScopeListeners();
return this;
};
/**
* @inheritDoc
*/
Scope.prototype.setTag = function (key, value) {
var _a;
this._tags = tslib_es6_assign(tslib_es6_assign({}, this._tags), (_a = {}, _a[key] = value, _a));
this._notifyScopeListeners();
return this;
};
/**
* @inheritDoc
*/
Scope.prototype.setExtras = function (extras) {
this._extra = tslib_es6_assign(tslib_es6_assign({}, this._extra), extras);
this._notifyScopeListeners();
return this;
};
/**
* @inheritDoc
*/
Scope.prototype.setExtra = function (key, extra) {
var _a;
this._extra = tslib_es6_assign(tslib_es6_assign({}, this._extra), (_a = {}, _a[key] = extra, _a));
this._notifyScopeListeners();
return this;
};
/**
* @inheritDoc
*/
Scope.prototype.setFingerprint = function (fingerprint) {
this._fingerprint = fingerprint;
this._notifyScopeListeners();
return this;
};
/**
* @inheritDoc
*/
Scope.prototype.setLevel = function (level) {
this._level = level;
this._notifyScopeListeners();
return this;
};
/**
* @inheritDoc
*/
Scope.prototype.setTransactionName = function (name) {
this._transactionName = name;
this._notifyScopeListeners();
return this;
};
/**
* Can be removed in major version.
* @deprecated in favor of {@link this.setTransactionName}
*/
Scope.prototype.setTransaction = function (name) {
return this.setTransactionName(name);
};
/**
* @inheritDoc
*/
Scope.prototype.setContext = function (key, context) {
var _a;
if (context === null) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete this._contexts[key];
}
else {
this._contexts = tslib_es6_assign(tslib_es6_assign({}, this._contexts), (_a = {}, _a[key] = context, _a));
}
this._notifyScopeListeners();
return this;
};
/**
* @inheritDoc
*/
Scope.prototype.setSpan = function (span) {
this._span = span;
this._notifyScopeListeners();
return this;
};
/**
* @inheritDoc
*/
Scope.prototype.getSpan = function () {
return this._span;
};
/**
* @inheritDoc
*/
Scope.prototype.getTransaction = function () {
var _a, _b, _c, _d;
// often, this span will be a transaction, but it's not guaranteed to be
var span = this.getSpan();
// try it the new way first
if ((_a = span) === null || _a === void 0 ? void 0 : _a.transaction) {
return (_b = span) === null || _b === void 0 ? void 0 : _b.transaction;
}
// fallback to the old way (known bug: this only finds transactions with sampled = true)
if ((_d = (_c = span) === null || _c === void 0 ? void 0 : _c.spanRecorder) === null || _d === void 0 ? void 0 : _d.spans[0]) {
return span.spanRecorder.spans[0];
}
// neither way found a transaction
return undefined;
};
/**
* @inheritDoc
*/
Scope.prototype.setSession = function (session) {
if (!session) {
delete this._session;
}
else {
this._session = session;
}
this._notifyScopeListeners();
return this;
};
/**
* @inheritDoc
*/
Scope.prototype.getSession = function () {
return this._session;
};
/**
* @inheritDoc
*/
Scope.prototype.update = function (captureContext) {
if (!captureContext) {
return this;
}
if (typeof captureContext === 'function') {
var updatedScope = captureContext(this);
return updatedScope instanceof Scope ? updatedScope : this;
}
if (captureContext instanceof Scope) {
this._tags = tslib_es6_assign(tslib_es6_assign({}, this._tags), captureContext._tags);
this._extra = tslib_es6_assign(tslib_es6_assign({}, this._extra), captureContext._extra);
this._contexts = tslib_es6_assign(tslib_es6_assign({}, this._contexts), captureContext._contexts);
if (captureContext._user && Object.keys(captureContext._user).length) {
this._user = captureContext._user;
}
if (captureContext._level) {
this._level = captureContext._level;
}
if (captureContext._fingerprint) {
this._fingerprint = captureContext._fingerprint;
}
}
else if (isPlainObject(captureContext)) {
// eslint-disable-next-line no-param-reassign
captureContext = captureContext;
this._tags = tslib_es6_assign(tslib_es6_assign({}, this._tags), captureContext.tags);
this._extra = tslib_es6_assign(tslib_es6_assign({}, this._extra), captureContext.extra);
this._contexts = tslib_es6_assign(tslib_es6_assign({}, this._contexts), captureContext.contexts);
if (captureContext.user) {
this._user = captureContext.user;
}
if (captureContext.level) {
this._level = captureContext.level;
}
if (captureContext.fingerprint) {
this._fingerprint = captureContext.fingerprint;
}
}
return this;
};
/**
* @inheritDoc
*/
Scope.prototype.clear = function () {
this._breadcrumbs = [];
this._tags = {};
this._extra = {};
this._user = {};
this._contexts = {};
this._level = undefined;
this._transactionName = undefined;
this._fingerprint = undefined;
this._span = undefined;
this._session = undefined;
this._notifyScopeListeners();
return this;
};
/**
* @inheritDoc
*/
Scope.prototype.addBreadcrumb = function (breadcrumb, maxBreadcrumbs) {
var mergedBreadcrumb = tslib_es6_assign({ timestamp: (0,time/* dateTimestampInSeconds */.yW)() }, breadcrumb);
this._breadcrumbs =
maxBreadcrumbs !== undefined && maxBreadcrumbs >= 0
? tslib_es6_spread(this._breadcrumbs, [mergedBreadcrumb]).slice(-maxBreadcrumbs)
: tslib_es6_spread(this._breadcrumbs, [mergedBreadcrumb]);
this._notifyScopeListeners();
return this;
};
/**
* @inheritDoc
*/
Scope.prototype.clearBreadcrumbs = function () {
this._breadcrumbs = [];
this._notifyScopeListeners();
return this;
};
/**
* Applies the current context and fingerprint to the event.
* Note that breadcrumbs will be added by the client.
* Also if the event has already breadcrumbs on it, we do not merge them.
* @param event Event
* @param hint May contain additional informartion about the original exception.
* @hidden
*/
Scope.prototype.applyToEvent = function (event, hint) {
var _a;
if (this._extra && Object.keys(this._extra).length) {
event.extra = tslib_es6_assign(tslib_es6_assign({}, this._extra), event.extra);
}
if (this._tags && Object.keys(this._tags).length) {
event.tags = tslib_es6_assign(tslib_es6_assign({}, this._tags), event.tags);
}
if (this._user && Object.keys(this._user).length) {
event.user = tslib_es6_assign(tslib_es6_assign({}, this._user), event.user);
}
if (this._contexts && Object.keys(this._contexts).length) {
event.contexts = tslib_es6_assign(tslib_es6_assign({}, this._contexts), event.contexts);
}
if (this._level) {
event.level = this._level;
}
if (this._transactionName) {
event.transaction = this._transactionName;
}
// We want to set the trace context for normal events only if there isn't already
// a trace context on the event. There is a product feature in place where we link
// errors with transaction and it relys on that.
if (this._span) {
event.contexts = tslib_es6_assign({ trace: this._span.getTraceContext() }, event.contexts);
var transactionName = (_a = this._span.transaction) === null || _a === void 0 ? void 0 : _a.name;
if (transactionName) {
event.tags = tslib_es6_assign({ transaction: transactionName }, event.tags);
}
}
this._applyFingerprint(event);
event.breadcrumbs = tslib_es6_spread((event.breadcrumbs || []), this._breadcrumbs);
event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;
return this._notifyEventProcessors(tslib_es6_spread(getGlobalEventProcessors(), this._eventProcessors), event, hint);
};
/**
* This will be called after {@link applyToEvent} is finished.
*/
Scope.prototype._notifyEventProcessors = function (processors, event, hint, index) {
var _this = this;
if (index === void 0) { index = 0; }
return new syncpromise_SyncPromise(function (resolve, reject) {
var processor = processors[index];
if (event === null || typeof processor !== 'function') {
resolve(event);
}
else {
var result = processor(tslib_es6_assign({}, event), hint);
if (isThenable(result)) {
result
.then(function (final) { return _this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve); })
.then(null, reject);
}
else {
_this._notifyEventProcessors(processors, result, hint, index + 1)
.then(resolve)
.then(null, reject);
}
}
});
};
/**
* This will be called on every set call.
*/
Scope.prototype._notifyScopeListeners = function () {
var _this = this;
// We need this check for this._notifyingListeners to be able to work on scope during updates
// If this check is not here we'll produce endless recursion when something is done with the scope
// during the callback.
if (!this._notifyingListeners) {
this._notifyingListeners = true;
this._scopeListeners.forEach(function (callback) {
callback(_this);
});
this._notifyingListeners = false;
}
};
/**
* Applies fingerprint from the scope to the event if there's one,
* uses message if there's one instead or get rid of empty fingerprint
*/
Scope.prototype._applyFingerprint = function (event) {
// Make sure it's an array first and we actually have something in place
event.fingerprint = event.fingerprint
? Array.isArray(event.fingerprint)
? event.fingerprint
: [event.fingerprint]
: [];
// If we have something on the scope, then merge it with event
if (this._fingerprint) {
event.fingerprint = event.fingerprint.concat(this._fingerprint);
}
// If we have no data at all, remove empty array default
if (event.fingerprint && !event.fingerprint.length) {
delete event.fingerprint;
}
};
return Scope;
}());
/**
* Retruns the global event processors.
*/
function getGlobalEventProcessors() {
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */
var global = (0,misc/* getGlobalObject */.Rf)();
global.__SENTRY__ = global.__SENTRY__ || {};
global.__SENTRY__.globalEventProcessors = global.__SENTRY__.globalEventProcessors || [];
return global.__SENTRY__.globalEventProcessors;
/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */
}
/**
* Add a EventProcessor to be kept globally.
* @param callback EventProcessor to add
*/
function addGlobalEventProcessor(callback) {
getGlobalEventProcessors().push(callback);
}
//# sourceMappingURL=scope.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/utils/esm/logger.js
/* eslint-disable @typescript-eslint/no-explicit-any */
// TODO: Implement different loggers for different environments
var global = (0,misc/* getGlobalObject */.Rf)();
/** Prefix for logging strings */
var PREFIX = 'Sentry Logger ';
/** JSDoc */
var Logger = /** @class */ (function () {
/** JSDoc */
function Logger() {
this._enabled = false;
}
/** JSDoc */
Logger.prototype.disable = function () {
this._enabled = false;
};
/** JSDoc */
Logger.prototype.enable = function () {
this._enabled = true;
};
/** JSDoc */
Logger.prototype.log = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!this._enabled) {
return;
}
(0,misc/* consoleSandbox */.Cf)(function () {
global.console.log(PREFIX + "[Log]: " + args.join(' '));
});
};
/** JSDoc */
Logger.prototype.warn = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!this._enabled) {
return;
}
(0,misc/* consoleSandbox */.Cf)(function () {
global.console.warn(PREFIX + "[Warn]: " + args.join(' '));
});
};
/** JSDoc */
Logger.prototype.error = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!this._enabled) {
return;
}
(0,misc/* consoleSandbox */.Cf)(function () {
global.console.error(PREFIX + "[Error]: " + args.join(' '));
});
};
return Logger;
}());
// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used
global.__SENTRY__ = global.__SENTRY__ || {};
var logger = global.__SENTRY__.logger || (global.__SENTRY__.logger = new Logger());
//# sourceMappingURL=logger.js.map
// EXTERNAL MODULE: ./node_modules/@sentry/utils/esm/node.js
var node = __webpack_require__(422);
;// CONCATENATED MODULE: ./node_modules/@sentry/types/esm/session.js
/**
* Session Status
*/
var SessionStatus;
(function (SessionStatus) {
/** JSDoc */
SessionStatus["Ok"] = "ok";
/** JSDoc */
SessionStatus["Exited"] = "exited";
/** JSDoc */
SessionStatus["Crashed"] = "crashed";
/** JSDoc */
SessionStatus["Abnormal"] = "abnormal";
})(SessionStatus || (SessionStatus = {}));
//# sourceMappingURL=session.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/utils/esm/browser.js
/**
* Given a child DOM element, returns a query-selector statement describing that
* and its ancestors
* e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
* @returns generated DOM path
*/
function htmlTreeAsString(elem) {
// try/catch both:
// - accessing event.target (see getsentry/raven-js#838, #768)
// - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly
// - can throw an exception in some circumstances.
try {
var currentElem = elem;
var MAX_TRAVERSE_HEIGHT = 5;
var MAX_OUTPUT_LEN = 80;
var out = [];
var height = 0;
var len = 0;
var separator = ' > ';
var sepLength = separator.length;
var nextStr = void 0;
// eslint-disable-next-line no-plusplus
while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {
nextStr = _htmlElementAsString(currentElem);
// bail out if
// - nextStr is the 'html' element
// - the length of the string that would be created exceeds MAX_OUTPUT_LEN
// (ignore this limit if we are on the first iteration)
if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) {
break;
}
out.push(nextStr);
len += nextStr.length;
currentElem = currentElem.parentNode;
}
return out.reverse().join(separator);
}
catch (_oO) {
return '';
}
}
/**
* Returns a simple, query-selector representation of a DOM element
* e.g. [HTMLElement] => input#foo.btn[name=baz]
* @returns generated DOM path
*/
function _htmlElementAsString(el) {
var elem = el;
var out = [];
var className;
var classes;
var key;
var attr;
var i;
if (!elem || !elem.tagName) {
return '';
}
out.push(elem.tagName.toLowerCase());
if (elem.id) {
out.push("#" + elem.id);
}
// eslint-disable-next-line prefer-const
className = elem.className;
if (className && isString(className)) {
classes = className.split(/\s+/);
for (i = 0; i < classes.length; i++) {
out.push("." + classes[i]);
}
}
var allowedAttrs = ['type', 'name', 'title', 'alt'];
for (i = 0; i < allowedAttrs.length; i++) {
key = allowedAttrs[i];
attr = elem.getAttribute(key);
if (attr) {
out.push("[" + key + "=\"" + attr + "\"]");
}
}
return out.join('');
}
//# sourceMappingURL=browser.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/utils/esm/memo.js
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/**
* Memo class used for decycle json objects. Uses WeakSet if available otherwise array.
*/
var Memo = /** @class */ (function () {
function Memo() {
this._hasWeakSet = typeof WeakSet === 'function';
this._inner = this._hasWeakSet ? new WeakSet() : [];
}
/**
* Sets obj to remember.
* @param obj Object to remember
*/
Memo.prototype.memoize = function (obj) {
if (this._hasWeakSet) {
if (this._inner.has(obj)) {
return true;
}
this._inner.add(obj);
return false;
}
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (var i = 0; i < this._inner.length; i++) {
var value = this._inner[i];
if (value === obj) {
return true;
}
}
this._inner.push(obj);
return false;
};
/**
* Removes object from internal storage.
* @param obj Object to forget
*/
Memo.prototype.unmemoize = function (obj) {
if (this._hasWeakSet) {
this._inner.delete(obj);
}
else {
for (var i = 0; i < this._inner.length; i++) {
if (this._inner[i] === obj) {
this._inner.splice(i, 1);
break;
}
}
}
};
return Memo;
}());
//# sourceMappingURL=memo.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/utils/esm/stacktrace.js
var defaultFunctionName = '';
/**
* Safely extract function name from itself
*/
function getFunctionName(fn) {
try {
if (!fn || typeof fn !== 'function') {
return defaultFunctionName;
}
return fn.name || defaultFunctionName;
}
catch (e) {
// Just accessing custom props in some Selenium environments
// can cause a "Permission denied" exception (see raven-js#495).
return defaultFunctionName;
}
}
//# sourceMappingURL=stacktrace.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/utils/esm/string.js
/**
* Truncates given string to the maximum characters count
*
* @param str An object that contains serializable values
* @param max Maximum number of characters in truncated string (0 = unlimited)
* @returns string Encoded
*/
function truncate(str, max) {
if (max === void 0) { max = 0; }
if (typeof str !== 'string' || max === 0) {
return str;
}
return str.length <= max ? str : str.substr(0, max) + "...";
}
/**
* This is basically just `trim_line` from
* https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67
*
* @param str An object that contains serializable values
* @param max Maximum number of characters in truncated string
* @returns string Encoded
*/
function snipLine(line, colno) {
var newLine = line;
var ll = newLine.length;
if (ll <= 150) {
return newLine;
}
if (colno > ll) {
// eslint-disable-next-line no-param-reassign
colno = ll;
}
var start = Math.max(colno - 60, 0);
if (start < 5) {
start = 0;
}
var end = Math.min(start + 140, ll);
if (end > ll - 5) {
end = ll;
}
if (end === ll) {
start = Math.max(end - 140, 0);
}
newLine = newLine.slice(start, end);
if (start > 0) {
newLine = "'{snip} " + newLine;
}
if (end < ll) {
newLine += ' {snip}';
}
return newLine;
}
/**
* Join values in array
* @param input array of values to be joined together
* @param delimiter string to be placed in-between values
* @returns Joined values
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function safeJoin(input, delimiter) {
if (!Array.isArray(input)) {
return '';
}
var output = [];
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (var i = 0; i < input.length; i++) {
var value = input[i];
try {
output.push(String(value));
}
catch (e) {
output.push('[value cannot be serialized]');
}
}
return output.join(delimiter);
}
/**
* Checks if the value matches a regex or includes the string
* @param value The string value to be checked against
* @param pattern Either a regex or a string that must be contained in value
*/
function isMatchingPattern(value, pattern) {
if (!isString(value)) {
return false;
}
if (isRegExp(pattern)) {
return pattern.test(value);
}
if (typeof pattern === 'string') {
return value.indexOf(pattern) !== -1;
}
return false;
}
//# sourceMappingURL=string.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/utils/esm/object.js
/**
* Wrap a given object method with a higher-order function
*
* @param source An object that contains a method to be wrapped.
* @param name A name of method to be wrapped.
* @param replacementFactory A function that should be used to wrap a given method, returning the wrapped method which
* will be substituted in for `source[name]`.
* @returns void
*/
function fill(source, name, replacementFactory) {
if (!(name in source)) {
return;
}
var original = source[name];
var wrapped = replacementFactory(original);
// Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work
// otherwise it'll throw "TypeError: Object.defineProperties called on non-object"
if (typeof wrapped === 'function') {
try {
wrapped.prototype = wrapped.prototype || {};
Object.defineProperties(wrapped, {
__sentry_original__: {
enumerable: false,
value: original,
},
});
}
catch (_Oo) {
// This can throw if multiple fill happens on a global object like XMLHttpRequest
// Fixes https://github.com/getsentry/sentry-javascript/issues/2043
}
}
source[name] = wrapped;
}
/**
* Encodes given object into url-friendly format
*
* @param object An object that contains serializable values
* @returns string Encoded
*/
function urlEncode(object) {
return Object.keys(object)
.map(function (key) { return encodeURIComponent(key) + "=" + encodeURIComponent(object[key]); })
.join('&');
}
/**
* Transforms any object into an object literal with all its attributes
* attached to it.
*
* @param value Initial source that we have to transform in order for it to be usable by the serializer
*/
function getWalkSource(value) {
if (isError(value)) {
var error = value;
var err = {
message: error.message,
name: error.name,
stack: error.stack,
};
for (var i in error) {
if (Object.prototype.hasOwnProperty.call(error, i)) {
err[i] = error[i];
}
}
return err;
}
if (isEvent(value)) {
var event_1 = value;
var source = {};
source.type = event_1.type;
// Accessing event.target can throw (see getsentry/raven-js#838, #768)
try {
source.target = isElement(event_1.target)
? htmlTreeAsString(event_1.target)
: Object.prototype.toString.call(event_1.target);
}
catch (_oO) {
source.target = '';
}
try {
source.currentTarget = isElement(event_1.currentTarget)
? htmlTreeAsString(event_1.currentTarget)
: Object.prototype.toString.call(event_1.currentTarget);
}
catch (_oO) {
source.currentTarget = '';
}
if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {
source.detail = event_1.detail;
}
for (var i in event_1) {
if (Object.prototype.hasOwnProperty.call(event_1, i)) {
source[i] = event_1;
}
}
return source;
}
return value;
}
/** Calculates bytes size of input string */
function utf8Length(value) {
// eslint-disable-next-line no-bitwise
return ~-encodeURI(value).split(/%..|./).length;
}
/** Calculates bytes size of input object */
function jsonSize(value) {
return utf8Length(JSON.stringify(value));
}
/** JSDoc */
function normalizeToSize(object,
// Default Node.js REPL depth
depth,
// 100kB, as 200kB is max payload size, so half sounds reasonable
maxSize) {
if (depth === void 0) { depth = 3; }
if (maxSize === void 0) { maxSize = 100 * 1024; }
var serialized = normalize(object, depth);
if (jsonSize(serialized) > maxSize) {
return normalizeToSize(object, depth - 1, maxSize);
}
return serialized;
}
/**
* Transform any non-primitive, BigInt, or Symbol-type value into a string. Acts as a no-op on strings, numbers,
* booleans, null, and undefined.
*
* @param value The value to stringify
* @returns For non-primitive, BigInt, and Symbol-type values, a string denoting the value's type, type and value, or
* type and `description` property, respectively. For non-BigInt, non-Symbol primitives, returns the original value,
* unchanged.
*/
function serializeValue(value) {
var type = Object.prototype.toString.call(value);
// Node.js REPL notation
if (typeof value === 'string') {
return value;
}
if (type === '[object Object]') {
return '[Object]';
}
if (type === '[object Array]') {
return '[Array]';
}
var normalized = normalizeValue(value);
return isPrimitive(normalized) ? normalized : type;
}
/**
* normalizeValue()
*
* Takes unserializable input and make it serializable friendly
*
* - translates undefined/NaN values to "[undefined]"/"[NaN]" respectively,
* - serializes Error objects
* - filter global objects
*/
function normalizeValue(value, key) {
if (key === 'domain' && value && typeof value === 'object' && value._events) {
return '[Domain]';
}
if (key === 'domainEmitter') {
return '[DomainEmitter]';
}
if (typeof __webpack_require__.g !== 'undefined' && value === __webpack_require__.g) {
return '[Global]';
}
if (typeof window !== 'undefined' && value === window) {
return '[Window]';
}
if (typeof document !== 'undefined' && value === document) {
return '[Document]';
}
// React's SyntheticEvent thingy
if (isSyntheticEvent(value)) {
return '[SyntheticEvent]';
}
if (typeof value === 'number' && value !== value) {
return '[NaN]';
}
if (value === void 0) {
return '[undefined]';
}
if (typeof value === 'function') {
return "[Function: " + getFunctionName(value) + "]";
}
// symbols and bigints are considered primitives by TS, but aren't natively JSON-serilaizable
if (typeof value === 'symbol') {
return "[" + String(value) + "]";
}
if (typeof value === 'bigint') {
return "[BigInt: " + String(value) + "]";
}
return value;
}
/**
* Walks an object to perform a normalization on it
*
* @param key of object that's walked in current iteration
* @param value object to be walked
* @param depth Optional number indicating how deep should walking be performed
* @param memo Optional Memo class handling decycling
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function walk(key, value, depth, memo) {
if (depth === void 0) { depth = +Infinity; }
if (memo === void 0) { memo = new Memo(); }
// If we reach the maximum depth, serialize whatever has left
if (depth === 0) {
return serializeValue(value);
}
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
// If value implements `toJSON` method, call it and return early
if (value !== null && value !== undefined && typeof value.toJSON === 'function') {
return value.toJSON();
}
/* eslint-enable @typescript-eslint/no-unsafe-member-access */
// If normalized value is a primitive, there are no branches left to walk, so we can just bail out, as theres no point in going down that branch any further
var normalized = normalizeValue(value, key);
if (isPrimitive(normalized)) {
return normalized;
}
// Create source that we will use for next itterations, either objectified error object (Error type with extracted keys:value pairs) or the input itself
var source = getWalkSource(value);
// Create an accumulator that will act as a parent for all future itterations of that branch
var acc = Array.isArray(value) ? [] : {};
// If we already walked that branch, bail out, as it's circular reference
if (memo.memoize(value)) {
return '[Circular ~]';
}
// Walk all keys of the source
for (var innerKey in source) {
// Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.
if (!Object.prototype.hasOwnProperty.call(source, innerKey)) {
continue;
}
// Recursively walk through all the child nodes
acc[innerKey] = walk(innerKey, source[innerKey], depth - 1, memo);
}
// Once walked through all the branches, remove the parent from memo storage
memo.unmemoize(value);
// Return accumulated values
return acc;
}
/**
* normalize()
*
* - Creates a copy to prevent original input mutation
* - Skip non-enumerablers
* - Calls `toJSON` if implemented
* - Removes circular references
* - Translates non-serializeable values (undefined/NaN/Functions) to serializable format
* - Translates known global objects/Classes to a string representations
* - Takes care of Error objects serialization
* - Optionally limit depth of final output
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function normalize(input, depth) {
try {
return JSON.parse(JSON.stringify(input, function (key, value) { return walk(key, value, depth); }));
}
catch (_oO) {
return '**non-serializable**';
}
}
/**
* Given any captured exception, extract its keys and create a sorted
* and truncated list that will be used inside the event message.
* eg. `Non-error exception captured with keys: foo, bar, baz`
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function extractExceptionKeysForMessage(exception, maxLength) {
if (maxLength === void 0) { maxLength = 40; }
var keys = Object.keys(getWalkSource(exception));
keys.sort();
if (!keys.length) {
return '[object has no keys]';
}
if (keys[0].length >= maxLength) {
return truncate(keys[0], maxLength);
}
for (var includedKeys = keys.length; includedKeys > 0; includedKeys--) {
var serialized = keys.slice(0, includedKeys).join(', ');
if (serialized.length > maxLength) {
continue;
}
if (includedKeys === keys.length) {
return serialized;
}
return truncate(serialized, maxLength);
}
return '';
}
/**
* Given any object, return the new object with removed keys that value was `undefined`.
* Works recursively on objects and arrays.
*/
function dropUndefinedKeys(val) {
var e_1, _a;
if (isPlainObject(val)) {
var obj = val;
var rv = {};
try {
for (var _b = __values(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) {
var key = _c.value;
if (typeof obj[key] !== 'undefined') {
rv[key] = dropUndefinedKeys(obj[key]);
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
return rv;
}
if (Array.isArray(val)) {
return val.map(dropUndefinedKeys);
}
return val;
}
//# sourceMappingURL=object.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/hub/esm/session.js
/**
* @inheritdoc
*/
var Session = /** @class */ (function () {
function Session(context) {
this.errors = 0;
this.sid = (0,misc/* uuid4 */.DM)();
this.timestamp = Date.now();
this.started = Date.now();
this.duration = 0;
this.status = SessionStatus.Ok;
if (context) {
this.update(context);
}
}
/** JSDoc */
// eslint-disable-next-line complexity
Session.prototype.update = function (context) {
if (context === void 0) { context = {}; }
if (context.user) {
if (context.user.ip_address) {
this.ipAddress = context.user.ip_address;
}
if (!context.did) {
this.did = context.user.id || context.user.email || context.user.username;
}
}
this.timestamp = context.timestamp || Date.now();
if (context.sid) {
// Good enough uuid validation. — Kamil
this.sid = context.sid.length === 32 ? context.sid : (0,misc/* uuid4 */.DM)();
}
if (context.did) {
this.did = "" + context.did;
}
if (typeof context.started === 'number') {
this.started = context.started;
}
if (typeof context.duration === 'number') {
this.duration = context.duration;
}
else {
this.duration = this.timestamp - this.started;
}
if (context.release) {
this.release = context.release;
}
if (context.environment) {
this.environment = context.environment;
}
if (context.ipAddress) {
this.ipAddress = context.ipAddress;
}
if (context.userAgent) {
this.userAgent = context.userAgent;
}
if (typeof context.errors === 'number') {
this.errors = context.errors;
}
if (context.status) {
this.status = context.status;
}
};
/** JSDoc */
Session.prototype.close = function (status) {
if (status) {
this.update({ status: status });
}
else if (this.status === SessionStatus.Ok) {
this.update({ status: SessionStatus.Exited });
}
else {
this.update();
}
};
/** JSDoc */
Session.prototype.toJSON = function () {
return dropUndefinedKeys({
sid: "" + this.sid,
init: true,
started: new Date(this.started).toISOString(),
timestamp: new Date(this.timestamp).toISOString(),
status: this.status,
errors: this.errors,
did: typeof this.did === 'number' || typeof this.did === 'string' ? "" + this.did : undefined,
duration: this.duration,
attrs: dropUndefinedKeys({
release: this.release,
environment: this.environment,
ip_address: this.ipAddress,
user_agent: this.userAgent,
}),
});
};
return Session;
}());
//# sourceMappingURL=session.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/hub/esm/hub.js
/**
* API compatibility version of this hub.
*
* WARNING: This number should only be increased when the global interface
* changes and new methods are introduced.
*
* @hidden
*/
var API_VERSION = 3;
/**
* Default maximum number of breadcrumbs added to an event. Can be overwritten
* with {@link Options.maxBreadcrumbs}.
*/
var DEFAULT_BREADCRUMBS = 100;
/**
* Absolute maximum number of breadcrumbs added to an event. The
* `maxBreadcrumbs` option cannot be higher than this value.
*/
var MAX_BREADCRUMBS = 100;
/**
* @inheritDoc
*/
var Hub = /** @class */ (function () {
/**
* Creates a new instance of the hub, will push one {@link Layer} into the
* internal stack on creation.
*
* @param client bound to the hub.
* @param scope bound to the hub.
* @param version number, higher number means higher priority.
*/
function Hub(client, scope, _version) {
if (scope === void 0) { scope = new Scope(); }
if (_version === void 0) { _version = API_VERSION; }
this._version = _version;
/** Is a {@link Layer}[] containing the client and scope */
this._stack = [{}];
this.getStackTop().scope = scope;
this.bindClient(client);
}
/**
* @inheritDoc
*/
Hub.prototype.isOlderThan = function (version) {
return this._version < version;
};
/**
* @inheritDoc
*/
Hub.prototype.bindClient = function (client) {
var top = this.getStackTop();
top.client = client;
if (client && client.setupIntegrations) {
client.setupIntegrations();
}
};
/**
* @inheritDoc
*/
Hub.prototype.pushScope = function () {
// We want to clone the content of prev scope
var scope = Scope.clone(this.getScope());
this.getStack().push({
client: this.getClient(),
scope: scope,
});
return scope;
};
/**
* @inheritDoc
*/
Hub.prototype.popScope = function () {
if (this.getStack().length <= 1)
return false;
return !!this.getStack().pop();
};
/**
* @inheritDoc
*/
Hub.prototype.withScope = function (callback) {
var scope = this.pushScope();
try {
callback(scope);
}
finally {
this.popScope();
}
};
/**
* @inheritDoc
*/
Hub.prototype.getClient = function () {
return this.getStackTop().client;
};
/** Returns the scope of the top stack. */
Hub.prototype.getScope = function () {
return this.getStackTop().scope;
};
/** Returns the scope stack for domains or the process. */
Hub.prototype.getStack = function () {
return this._stack;
};
/** Returns the topmost scope layer in the order domain > local > process. */
Hub.prototype.getStackTop = function () {
return this._stack[this._stack.length - 1];
};
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
Hub.prototype.captureException = function (exception, hint) {
var eventId = (this._lastEventId = (0,misc/* uuid4 */.DM)());
var finalHint = hint;
// If there's no explicit hint provided, mimick the same thing that would happen
// in the minimal itself to create a consistent behavior.
// We don't do this in the client, as it's the lowest level API, and doing this,
// would prevent user from having full control over direct calls.
if (!hint) {
var syntheticException = void 0;
try {
throw new Error('Sentry syntheticException');
}
catch (exception) {
syntheticException = exception;
}
finalHint = {
originalException: exception,
syntheticException: syntheticException,
};
}
this._invokeClient('captureException', exception, tslib_es6_assign(tslib_es6_assign({}, finalHint), { event_id: eventId }));
return eventId;
};
/**
* @inheritDoc
*/
Hub.prototype.captureMessage = function (message, level, hint) {
var eventId = (this._lastEventId = (0,misc/* uuid4 */.DM)());
var finalHint = hint;
// If there's no explicit hint provided, mimick the same thing that would happen
// in the minimal itself to create a consistent behavior.
// We don't do this in the client, as it's the lowest level API, and doing this,
// would prevent user from having full control over direct calls.
if (!hint) {
var syntheticException = void 0;
try {
throw new Error(message);
}
catch (exception) {
syntheticException = exception;
}
finalHint = {
originalException: message,
syntheticException: syntheticException,
};
}
this._invokeClient('captureMessage', message, level, tslib_es6_assign(tslib_es6_assign({}, finalHint), { event_id: eventId }));
return eventId;
};
/**
* @inheritDoc
*/
Hub.prototype.captureEvent = function (event, hint) {
var eventId = (this._lastEventId = (0,misc/* uuid4 */.DM)());
this._invokeClient('captureEvent', event, tslib_es6_assign(tslib_es6_assign({}, hint), { event_id: eventId }));
return eventId;
};
/**
* @inheritDoc
*/
Hub.prototype.lastEventId = function () {
return this._lastEventId;
};
/**
* @inheritDoc
*/
Hub.prototype.addBreadcrumb = function (breadcrumb, hint) {
var _a = this.getStackTop(), scope = _a.scope, client = _a.client;
if (!scope || !client)
return;
// eslint-disable-next-line @typescript-eslint/unbound-method
var _b = (client.getOptions && client.getOptions()) || {}, _c = _b.beforeBreadcrumb, beforeBreadcrumb = _c === void 0 ? null : _c, _d = _b.maxBreadcrumbs, maxBreadcrumbs = _d === void 0 ? DEFAULT_BREADCRUMBS : _d;
if (maxBreadcrumbs <= 0)
return;
var timestamp = (0,time/* dateTimestampInSeconds */.yW)();
var mergedBreadcrumb = tslib_es6_assign({ timestamp: timestamp }, breadcrumb);
var finalBreadcrumb = beforeBreadcrumb
? (0,misc/* consoleSandbox */.Cf)(function () { return beforeBreadcrumb(mergedBreadcrumb, hint); })
: mergedBreadcrumb;
if (finalBreadcrumb === null)
return;
scope.addBreadcrumb(finalBreadcrumb, Math.min(maxBreadcrumbs, MAX_BREADCRUMBS));
};
/**
* @inheritDoc
*/
Hub.prototype.setUser = function (user) {
var scope = this.getScope();
if (scope)
scope.setUser(user);
};
/**
* @inheritDoc
*/
Hub.prototype.setTags = function (tags) {
var scope = this.getScope();
if (scope)
scope.setTags(tags);
};
/**
* @inheritDoc
*/
Hub.prototype.setExtras = function (extras) {
var scope = this.getScope();
if (scope)
scope.setExtras(extras);
};
/**
* @inheritDoc
*/
Hub.prototype.setTag = function (key, value) {
var scope = this.getScope();
if (scope)
scope.setTag(key, value);
};
/**
* @inheritDoc
*/
Hub.prototype.setExtra = function (key, extra) {
var scope = this.getScope();
if (scope)
scope.setExtra(key, extra);
};
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Hub.prototype.setContext = function (name, context) {
var scope = this.getScope();
if (scope)
scope.setContext(name, context);
};
/**
* @inheritDoc
*/
Hub.prototype.configureScope = function (callback) {
var _a = this.getStackTop(), scope = _a.scope, client = _a.client;
if (scope && client) {
callback(scope);
}
};
/**
* @inheritDoc
*/
Hub.prototype.run = function (callback) {
var oldHub = makeMain(this);
try {
callback(this);
}
finally {
makeMain(oldHub);
}
};
/**
* @inheritDoc
*/
Hub.prototype.getIntegration = function (integration) {
var client = this.getClient();
if (!client)
return null;
try {
return client.getIntegration(integration);
}
catch (_oO) {
logger.warn("Cannot retrieve integration " + integration.id + " from the current Hub");
return null;
}
};
/**
* @inheritDoc
*/
Hub.prototype.startSpan = function (context) {
return this._callExtensionMethod('startSpan', context);
};
/**
* @inheritDoc
*/
Hub.prototype.startTransaction = function (context, customSamplingContext) {
return this._callExtensionMethod('startTransaction', context, customSamplingContext);
};
/**
* @inheritDoc
*/
Hub.prototype.traceHeaders = function () {
return this._callExtensionMethod('traceHeaders');
};
/**
* @inheritDoc
*/
Hub.prototype.startSession = function (context) {
// End existing session if there's one
this.endSession();
var _a = this.getStackTop(), scope = _a.scope, client = _a.client;
var _b = (client && client.getOptions()) || {}, release = _b.release, environment = _b.environment;
var session = new Session(tslib_es6_assign(tslib_es6_assign({ release: release,
environment: environment }, (scope && { user: scope.getUser() })), context));
if (scope) {
scope.setSession(session);
}
return session;
};
/**
* @inheritDoc
*/
Hub.prototype.endSession = function () {
var _a = this.getStackTop(), scope = _a.scope, client = _a.client;
if (!scope)
return;
var session = scope.getSession && scope.getSession();
if (session) {
session.close();
if (client && client.captureSession) {
client.captureSession(session);
}
scope.setSession();
}
};
/**
* Internal helper function to call a method on the top client if it exists.
*
* @param method The method to call on the client.
* @param args Arguments to pass to the client function.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Hub.prototype._invokeClient = function (method) {
var _a;
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
var _b = this.getStackTop(), scope = _b.scope, client = _b.client;
if (client && client[method]) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
(_a = client)[method].apply(_a, tslib_es6_spread(args, [scope]));
}
};
/**
* Calls global extension method and binding current instance to the function call
*/
// @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Hub.prototype._callExtensionMethod = function (method) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
var carrier = getMainCarrier();
var sentry = carrier.__SENTRY__;
if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {
return sentry.extensions[method].apply(this, args);
}
logger.warn("Extension method " + method + " couldn't be found, doing nothing.");
};
return Hub;
}());
/** Returns the global shim registry. */
function getMainCarrier() {
var carrier = (0,misc/* getGlobalObject */.Rf)();
carrier.__SENTRY__ = carrier.__SENTRY__ || {
extensions: {},
hub: undefined,
};
return carrier;
}
/**
* Replaces the current main hub with the passed one on the global object
*
* @returns The old replaced hub
*/
function makeMain(hub) {
var registry = getMainCarrier();
var oldHub = getHubFromCarrier(registry);
setHubOnCarrier(registry, hub);
return oldHub;
}
/**
* Returns the default hub instance.
*
* If a hub is already registered in the global carrier but this module
* contains a more recent version, it replaces the registered version.
* Otherwise, the currently registered hub will be returned.
*/
function hub_getCurrentHub() {
// Get main carrier (global for every environment)
var registry = getMainCarrier();
// If there's no hub, or its an old API, assign a new one
if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {
setHubOnCarrier(registry, new Hub());
}
// Prefer domains over global if they are there (applicable only to Node environment)
if ((0,node/* isNodeEnv */.KV)()) {
return getHubFromActiveDomain(registry);
}
// Return hub that lives on a global object
return getHubFromCarrier(registry);
}
/**
* Returns the active domain, if one exists
*
* @returns The domain, or undefined if there is no active domain
*/
function getActiveDomain() {
var sentry = getMainCarrier().__SENTRY__;
return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;
}
/**
* Try to read the hub from an active domain, and fallback to the registry if one doesn't exist
* @returns discovered hub
*/
function getHubFromActiveDomain(registry) {
try {
var activeDomain = getActiveDomain();
// If there's no active domain, just return global hub
if (!activeDomain) {
return getHubFromCarrier(registry);
}
// If there's no hub on current domain, or it's an old API, assign a new one
if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) {
var registryHubTopStack = getHubFromCarrier(registry).getStackTop();
setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, Scope.clone(registryHubTopStack.scope)));
}
// Return hub that lives on a domain
return getHubFromCarrier(activeDomain);
}
catch (_Oo) {
// Return hub that lives on a global object
return getHubFromCarrier(registry);
}
}
/**
* This will tell whether a carrier has a hub on it or not
* @param carrier object
*/
function hasHubOnCarrier(carrier) {
return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);
}
/**
* This will create a new {@link Hub} and add to the passed object on
* __SENTRY__.hub.
* @param carrier object
* @hidden
*/
function getHubFromCarrier(carrier) {
if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub)
return carrier.__SENTRY__.hub;
carrier.__SENTRY__ = carrier.__SENTRY__ || {};
carrier.__SENTRY__.hub = new Hub();
return carrier.__SENTRY__.hub;
}
/**
* This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute
* @param carrier object
* @param hub Hub
*/
function setHubOnCarrier(carrier, hub) {
if (!carrier)
return false;
carrier.__SENTRY__ = carrier.__SENTRY__ || {};
carrier.__SENTRY__.hub = hub;
return true;
}
//# sourceMappingURL=hub.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/core/esm/integrations/inboundfilters.js
// "Script error." is hard coded into browsers for errors that it can't read.
// this is the result of a script being pulled in from an external domain and CORS.
var DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/];
/** Inbound filters configurable by the user */
var InboundFilters = /** @class */ (function () {
function InboundFilters(_options) {
if (_options === void 0) { _options = {}; }
this._options = _options;
/**
* @inheritDoc
*/
this.name = InboundFilters.id;
}
/**
* @inheritDoc
*/
InboundFilters.prototype.setupOnce = function () {
addGlobalEventProcessor(function (event) {
var hub = hub_getCurrentHub();
if (!hub) {
return event;
}
var self = hub.getIntegration(InboundFilters);
if (self) {
var client = hub.getClient();
var clientOptions = client ? client.getOptions() : {};
var options = self._mergeOptions(clientOptions);
if (self._shouldDropEvent(event, options)) {
return null;
}
}
return event;
});
};
/** JSDoc */
InboundFilters.prototype._shouldDropEvent = function (event, options) {
if (this._isSentryError(event, options)) {
logger.warn("Event dropped due to being internal Sentry Error.\nEvent: " + (0,misc/* getEventDescription */.jH)(event));
return true;
}
if (this._isIgnoredError(event, options)) {
logger.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: " + (0,misc/* getEventDescription */.jH)(event));
return true;
}
if (this._isDeniedUrl(event, options)) {
logger.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: " + (0,misc/* getEventDescription */.jH)(event) + ".\nUrl: " + this._getEventFilterUrl(event));
return true;
}
if (!this._isAllowedUrl(event, options)) {
logger.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: " + (0,misc/* getEventDescription */.jH)(event) + ".\nUrl: " + this._getEventFilterUrl(event));
return true;
}
return false;
};
/** JSDoc */
InboundFilters.prototype._isSentryError = function (event, options) {
if (!options.ignoreInternal) {
return false;
}
try {
return ((event &&
event.exception &&
event.exception.values &&
event.exception.values[0] &&
event.exception.values[0].type === 'SentryError') ||
false);
}
catch (_oO) {
return false;
}
};
/** JSDoc */
InboundFilters.prototype._isIgnoredError = function (event, options) {
if (!options.ignoreErrors || !options.ignoreErrors.length) {
return false;
}
return this._getPossibleEventMessages(event).some(function (message) {
// Not sure why TypeScript complains here...
return options.ignoreErrors.some(function (pattern) { return isMatchingPattern(message, pattern); });
});
};
/** JSDoc */
InboundFilters.prototype._isDeniedUrl = function (event, options) {
// TODO: Use Glob instead?
if (!options.denyUrls || !options.denyUrls.length) {
return false;
}
var url = this._getEventFilterUrl(event);
return !url ? false : options.denyUrls.some(function (pattern) { return isMatchingPattern(url, pattern); });
};
/** JSDoc */
InboundFilters.prototype._isAllowedUrl = function (event, options) {
// TODO: Use Glob instead?
if (!options.allowUrls || !options.allowUrls.length) {
return true;
}
var url = this._getEventFilterUrl(event);
return !url ? true : options.allowUrls.some(function (pattern) { return isMatchingPattern(url, pattern); });
};
/** JSDoc */
InboundFilters.prototype._mergeOptions = function (clientOptions) {
if (clientOptions === void 0) { clientOptions = {}; }
return {
allowUrls: tslib_es6_spread((this._options.whitelistUrls || []), (this._options.allowUrls || []), (clientOptions.whitelistUrls || []), (clientOptions.allowUrls || [])),
denyUrls: tslib_es6_spread((this._options.blacklistUrls || []), (this._options.denyUrls || []), (clientOptions.blacklistUrls || []), (clientOptions.denyUrls || [])),
ignoreErrors: tslib_es6_spread((this._options.ignoreErrors || []), (clientOptions.ignoreErrors || []), DEFAULT_IGNORE_ERRORS),
ignoreInternal: typeof this._options.ignoreInternal !== 'undefined' ? this._options.ignoreInternal : true,
};
};
/** JSDoc */
InboundFilters.prototype._getPossibleEventMessages = function (event) {
if (event.message) {
return [event.message];
}
if (event.exception) {
try {
var _a = (event.exception.values && event.exception.values[0]) || {}, _b = _a.type, type = _b === void 0 ? '' : _b, _c = _a.value, value = _c === void 0 ? '' : _c;
return ["" + value, type + ": " + value];
}
catch (oO) {
logger.error("Cannot extract message for event " + (0,misc/* getEventDescription */.jH)(event));
return [];
}
}
return [];
};
/** JSDoc */
InboundFilters.prototype._getEventFilterUrl = function (event) {
try {
if (event.stacktrace) {
var frames_1 = event.stacktrace.frames;
return (frames_1 && frames_1[frames_1.length - 1].filename) || null;
}
if (event.exception) {
var frames_2 = event.exception.values && event.exception.values[0].stacktrace && event.exception.values[0].stacktrace.frames;
return (frames_2 && frames_2[frames_2.length - 1].filename) || null;
}
return null;
}
catch (oO) {
logger.error("Cannot extract url for event " + (0,misc/* getEventDescription */.jH)(event));
return null;
}
};
/**
* @inheritDoc
*/
InboundFilters.id = 'InboundFilters';
return InboundFilters;
}());
//# sourceMappingURL=inboundfilters.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/core/esm/integrations/functiontostring.js
var originalFunctionToString;
/** Patch toString calls to return proper name for wrapped functions */
var FunctionToString = /** @class */ (function () {
function FunctionToString() {
/**
* @inheritDoc
*/
this.name = FunctionToString.id;
}
/**
* @inheritDoc
*/
FunctionToString.prototype.setupOnce = function () {
// eslint-disable-next-line @typescript-eslint/unbound-method
originalFunctionToString = Function.prototype.toString;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Function.prototype.toString = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var context = this.__sentry_original__ || this;
return originalFunctionToString.apply(context, args);
};
};
/**
* @inheritDoc
*/
FunctionToString.id = 'FunctionToString';
return FunctionToString;
}());
//# sourceMappingURL=functiontostring.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/core/esm/sdk.js
/**
* Internal function to create a new SDK client instance. The client is
* installed and then bound to the current scope.
*
* @param clientClass The client class to instantiate.
* @param options Options to pass to the client.
*/
function initAndBind(clientClass, options) {
if (options.debug === true) {
logger.enable();
}
var hub = hub_getCurrentHub();
var client = new clientClass(options);
hub.bindClient(client);
}
//# sourceMappingURL=sdk.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/utils/esm/polyfill.js
var setPrototypeOf = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties);
/**
* setPrototypeOf polyfill using __proto__
*/
// eslint-disable-next-line @typescript-eslint/ban-types
function setProtoOf(obj, proto) {
// @ts-ignore __proto__ does not exist on obj
obj.__proto__ = proto;
return obj;
}
/**
* setPrototypeOf polyfill using mixin
*/
// eslint-disable-next-line @typescript-eslint/ban-types
function mixinProperties(obj, proto) {
for (var prop in proto) {
// eslint-disable-next-line no-prototype-builtins
if (!obj.hasOwnProperty(prop)) {
// @ts-ignore typescript complains about indexing so we remove
obj[prop] = proto[prop];
}
}
return obj;
}
//# sourceMappingURL=polyfill.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/utils/esm/error.js
/** An error emitted by Sentry SDKs and related utilities. */
var SentryError = /** @class */ (function (_super) {
__extends(SentryError, _super);
function SentryError(message) {
var _newTarget = this.constructor;
var _this = _super.call(this, message) || this;
_this.message = message;
_this.name = _newTarget.prototype.constructor.name;
setPrototypeOf(_this, _newTarget.prototype);
return _this;
}
return SentryError;
}(Error));
//# sourceMappingURL=error.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/utils/esm/dsn.js
/** Regular expression used to parse a Dsn. */
var DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/;
/** Error message */
var ERROR_MESSAGE = 'Invalid Dsn';
/** The Sentry Dsn, identifying a Sentry instance and project. */
var Dsn = /** @class */ (function () {
/** Creates a new Dsn component */
function Dsn(from) {
if (typeof from === 'string') {
this._fromString(from);
}
else {
this._fromComponents(from);
}
this._validate();
}
/**
* Renders the string representation of this Dsn.
*
* By default, this will render the public representation without the password
* component. To get the deprecated private representation, set `withPassword`
* to true.
*
* @param withPassword When set to true, the password will be included.
*/
Dsn.prototype.toString = function (withPassword) {
if (withPassword === void 0) { withPassword = false; }
var _a = this, host = _a.host, path = _a.path, pass = _a.pass, port = _a.port, projectId = _a.projectId, protocol = _a.protocol, user = _a.user;
return (protocol + "://" + user + (withPassword && pass ? ":" + pass : '') +
("@" + host + (port ? ":" + port : '') + "/" + (path ? path + "/" : path) + projectId));
};
/** Parses a string into this Dsn. */
Dsn.prototype._fromString = function (str) {
var match = DSN_REGEX.exec(str);
if (!match) {
throw new SentryError(ERROR_MESSAGE);
}
var _a = __read(match.slice(1), 6), protocol = _a[0], user = _a[1], _b = _a[2], pass = _b === void 0 ? '' : _b, host = _a[3], _c = _a[4], port = _c === void 0 ? '' : _c, lastPath = _a[5];
var path = '';
var projectId = lastPath;
var split = projectId.split('/');
if (split.length > 1) {
path = split.slice(0, -1).join('/');
projectId = split.pop();
}
if (projectId) {
var projectMatch = projectId.match(/^\d+/);
if (projectMatch) {
projectId = projectMatch[0];
}
}
this._fromComponents({ host: host, pass: pass, path: path, projectId: projectId, port: port, protocol: protocol, user: user });
};
/** Maps Dsn components into this instance. */
Dsn.prototype._fromComponents = function (components) {
this.protocol = components.protocol;
this.user = components.user;
this.pass = components.pass || '';
this.host = components.host;
this.port = components.port || '';
this.path = components.path || '';
this.projectId = components.projectId;
};
/** Validates this Dsn and throws on error. */
Dsn.prototype._validate = function () {
var _this = this;
['protocol', 'user', 'host', 'projectId'].forEach(function (component) {
if (!_this[component]) {
throw new SentryError(ERROR_MESSAGE + ": " + component + " missing");
}
});
if (!this.projectId.match(/^\d+$/)) {
throw new SentryError(ERROR_MESSAGE + ": Invalid projectId " + this.projectId);
}
if (this.protocol !== 'http' && this.protocol !== 'https') {
throw new SentryError(ERROR_MESSAGE + ": Invalid protocol " + this.protocol);
}
if (this.port && isNaN(parseInt(this.port, 10))) {
throw new SentryError(ERROR_MESSAGE + ": Invalid port " + this.port);
}
};
return Dsn;
}());
//# sourceMappingURL=dsn.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/core/esm/integration.js
var installedIntegrations = [];
/** Gets integration to install */
function getIntegrationsToSetup(options) {
var defaultIntegrations = (options.defaultIntegrations && tslib_es6_spread(options.defaultIntegrations)) || [];
var userIntegrations = options.integrations;
var integrations = [];
if (Array.isArray(userIntegrations)) {
var userIntegrationsNames_1 = userIntegrations.map(function (i) { return i.name; });
var pickedIntegrationsNames_1 = [];
// Leave only unique default integrations, that were not overridden with provided user integrations
defaultIntegrations.forEach(function (defaultIntegration) {
if (userIntegrationsNames_1.indexOf(defaultIntegration.name) === -1 &&
pickedIntegrationsNames_1.indexOf(defaultIntegration.name) === -1) {
integrations.push(defaultIntegration);
pickedIntegrationsNames_1.push(defaultIntegration.name);
}
});
// Don't add same user integration twice
userIntegrations.forEach(function (userIntegration) {
if (pickedIntegrationsNames_1.indexOf(userIntegration.name) === -1) {
integrations.push(userIntegration);
pickedIntegrationsNames_1.push(userIntegration.name);
}
});
}
else if (typeof userIntegrations === 'function') {
integrations = userIntegrations(defaultIntegrations);
integrations = Array.isArray(integrations) ? integrations : [integrations];
}
else {
integrations = tslib_es6_spread(defaultIntegrations);
}
// Make sure that if present, `Debug` integration will always run last
var integrationsNames = integrations.map(function (i) { return i.name; });
var alwaysLastToRun = 'Debug';
if (integrationsNames.indexOf(alwaysLastToRun) !== -1) {
integrations.push.apply(integrations, tslib_es6_spread(integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1)));
}
return integrations;
}
/** Setup given integration */
function setupIntegration(integration) {
if (installedIntegrations.indexOf(integration.name) !== -1) {
return;
}
integration.setupOnce(addGlobalEventProcessor, hub_getCurrentHub);
installedIntegrations.push(integration.name);
logger.log("Integration installed: " + integration.name);
}
/**
* Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default
* integrations are added unless they were already provided before.
* @param integrations array of integration instances
* @param withDefault should enable default integrations
*/
function setupIntegrations(options) {
var integrations = {};
getIntegrationsToSetup(options).forEach(function (integration) {
integrations[integration.name] = integration;
setupIntegration(integration);
});
return integrations;
}
//# sourceMappingURL=integration.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/core/esm/baseclient.js
/* eslint-disable max-lines */
/**
* Base implementation for all JavaScript SDK clients.
*
* Call the constructor with the corresponding backend constructor and options
* specific to the client subclass. To access these options later, use
* {@link Client.getOptions}. Also, the Backend instance is available via
* {@link Client.getBackend}.
*
* If a Dsn is specified in the options, it will be parsed and stored. Use
* {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is
* invalid, the constructor will throw a {@link SentryException}. Note that
* without a valid Dsn, the SDK will not send any events to Sentry.
*
* Before sending an event via the backend, it is passed through
* {@link BaseClient.prepareEvent} to add SDK information and scope data
* (breadcrumbs and context). To add more custom information, override this
* method and extend the resulting prepared event.
*
* To issue automatically created events (e.g. via instrumentation), use
* {@link Client.captureEvent}. It will prepare the event and pass it through
* the callback lifecycle. To issue auto-breadcrumbs, use
* {@link Client.addBreadcrumb}.
*
* @example
* class NodeClient extends BaseClient {
* public constructor(options: NodeOptions) {
* super(NodeBackend, options);
* }
*
* // ...
* }
*/
var BaseClient = /** @class */ (function () {
/**
* Initializes this client instance.
*
* @param backendClass A constructor function to create the backend.
* @param options Options for the client.
*/
function BaseClient(backendClass, options) {
/** Array of used integrations. */
this._integrations = {};
/** Number of call being processed */
this._processing = 0;
this._backend = new backendClass(options);
this._options = options;
if (options.dsn) {
this._dsn = new Dsn(options.dsn);
}
}
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
BaseClient.prototype.captureException = function (exception, hint, scope) {
var _this = this;
var eventId = hint && hint.event_id;
this._process(this._getBackend()
.eventFromException(exception, hint)
.then(function (event) { return _this._captureEvent(event, hint, scope); })
.then(function (result) {
eventId = result;
}));
return eventId;
};
/**
* @inheritDoc
*/
BaseClient.prototype.captureMessage = function (message, level, hint, scope) {
var _this = this;
var eventId = hint && hint.event_id;
var promisedEvent = isPrimitive(message)
? this._getBackend().eventFromMessage(String(message), level, hint)
: this._getBackend().eventFromException(message, hint);
this._process(promisedEvent
.then(function (event) { return _this._captureEvent(event, hint, scope); })
.then(function (result) {
eventId = result;
}));
return eventId;
};
/**
* @inheritDoc
*/
BaseClient.prototype.captureEvent = function (event, hint, scope) {
var eventId = hint && hint.event_id;
this._process(this._captureEvent(event, hint, scope).then(function (result) {
eventId = result;
}));
return eventId;
};
/**
* @inheritDoc
*/
BaseClient.prototype.captureSession = function (session) {
if (!session.release) {
logger.warn('Discarded session because of missing release');
}
else {
this._sendSession(session);
}
};
/**
* @inheritDoc
*/
BaseClient.prototype.getDsn = function () {
return this._dsn;
};
/**
* @inheritDoc
*/
BaseClient.prototype.getOptions = function () {
return this._options;
};
/**
* @inheritDoc
*/
BaseClient.prototype.flush = function (timeout) {
var _this = this;
return this._isClientProcessing(timeout).then(function (ready) {
return _this._getBackend()
.getTransport()
.close(timeout)
.then(function (transportFlushed) { return ready && transportFlushed; });
});
};
/**
* @inheritDoc
*/
BaseClient.prototype.close = function (timeout) {
var _this = this;
return this.flush(timeout).then(function (result) {
_this.getOptions().enabled = false;
return result;
});
};
/**
* Sets up the integrations
*/
BaseClient.prototype.setupIntegrations = function () {
if (this._isEnabled()) {
this._integrations = setupIntegrations(this._options);
}
};
/**
* @inheritDoc
*/
BaseClient.prototype.getIntegration = function (integration) {
try {
return this._integrations[integration.id] || null;
}
catch (_oO) {
logger.warn("Cannot retrieve integration " + integration.id + " from the current Client");
return null;
}
};
/** Updates existing session based on the provided event */
BaseClient.prototype._updateSessionFromEvent = function (session, event) {
var e_1, _a;
var crashed = false;
var errored = false;
var userAgent;
var exceptions = event.exception && event.exception.values;
if (exceptions) {
errored = true;
try {
for (var exceptions_1 = __values(exceptions), exceptions_1_1 = exceptions_1.next(); !exceptions_1_1.done; exceptions_1_1 = exceptions_1.next()) {
var ex = exceptions_1_1.value;
var mechanism = ex.mechanism;
if (mechanism && mechanism.handled === false) {
crashed = true;
break;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (exceptions_1_1 && !exceptions_1_1.done && (_a = exceptions_1.return)) _a.call(exceptions_1);
}
finally { if (e_1) throw e_1.error; }
}
}
var user = event.user;
if (!session.userAgent) {
var headers = event.request ? event.request.headers : {};
for (var key in headers) {
if (key.toLowerCase() === 'user-agent') {
userAgent = headers[key];
break;
}
}
}
session.update(tslib_es6_assign(tslib_es6_assign({}, (crashed && { status: SessionStatus.Crashed })), { user: user,
userAgent: userAgent, errors: session.errors + Number(errored || crashed) }));
};
/** Deliver captured session to Sentry */
BaseClient.prototype._sendSession = function (session) {
this._getBackend().sendSession(session);
};
/** Waits for the client to be done with processing. */
BaseClient.prototype._isClientProcessing = function (timeout) {
var _this = this;
return new syncpromise_SyncPromise(function (resolve) {
var ticked = 0;
var tick = 1;
var interval = setInterval(function () {
if (_this._processing == 0) {
clearInterval(interval);
resolve(true);
}
else {
ticked += tick;
if (timeout && ticked >= timeout) {
clearInterval(interval);
resolve(false);
}
}
}, tick);
});
};
/** Returns the current backend. */
BaseClient.prototype._getBackend = function () {
return this._backend;
};
/** Determines whether this SDK is enabled and a valid Dsn is present. */
BaseClient.prototype._isEnabled = function () {
return this.getOptions().enabled !== false && this._dsn !== undefined;
};
/**
* Adds common information to events.
*
* The information includes release and environment from `options`,
* breadcrumbs and context (extra, tags and user) from the scope.
*
* Information that is already present in the event is never overwritten. For
* nested objects, such as the context, keys are merged.
*
* @param event The original event.
* @param hint May contain additional information about the original exception.
* @param scope A scope containing event metadata.
* @returns A new event with more information.
*/
BaseClient.prototype._prepareEvent = function (event, scope, hint) {
var _this = this;
var _a = this.getOptions().normalizeDepth, normalizeDepth = _a === void 0 ? 3 : _a;
var prepared = tslib_es6_assign(tslib_es6_assign({}, event), { event_id: event.event_id || (hint && hint.event_id ? hint.event_id : (0,misc/* uuid4 */.DM)()), timestamp: event.timestamp || (0,time/* dateTimestampInSeconds */.yW)() });
this._applyClientOptions(prepared);
this._applyIntegrationsMetadata(prepared);
// If we have scope given to us, use it as the base for further modifications.
// This allows us to prevent unnecessary copying of data if `captureContext` is not provided.
var finalScope = scope;
if (hint && hint.captureContext) {
finalScope = Scope.clone(finalScope).update(hint.captureContext);
}
// We prepare the result here with a resolved Event.
var result = syncpromise_SyncPromise.resolve(prepared);
// This should be the last thing called, since we want that
// {@link Hub.addEventProcessor} gets the finished prepared event.
if (finalScope) {
// In case we have a hub we reassign it.
result = finalScope.applyToEvent(prepared, hint);
}
return result.then(function (evt) {
if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {
return _this._normalizeEvent(evt, normalizeDepth);
}
return evt;
});
};
/**
* Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.
* Normalized keys:
* - `breadcrumbs.data`
* - `user`
* - `contexts`
* - `extra`
* @param event Event
* @returns Normalized event
*/
BaseClient.prototype._normalizeEvent = function (event, depth) {
if (!event) {
return null;
}
var normalized = tslib_es6_assign(tslib_es6_assign(tslib_es6_assign(tslib_es6_assign(tslib_es6_assign({}, event), (event.breadcrumbs && {
breadcrumbs: event.breadcrumbs.map(function (b) { return (tslib_es6_assign(tslib_es6_assign({}, b), (b.data && {
data: normalize(b.data, depth),
}))); }),
})), (event.user && {
user: normalize(event.user, depth),
})), (event.contexts && {
contexts: normalize(event.contexts, depth),
})), (event.extra && {
extra: normalize(event.extra, depth),
}));
// event.contexts.trace stores information about a Transaction. Similarly,
// event.spans[] stores information about child Spans. Given that a
// Transaction is conceptually a Span, normalization should apply to both
// Transactions and Spans consistently.
// For now the decision is to skip normalization of Transactions and Spans,
// so this block overwrites the normalized event to add back the original
// Transaction information prior to normalization.
if (event.contexts && event.contexts.trace) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
normalized.contexts.trace = event.contexts.trace;
}
return normalized;
};
/**
* Enhances event using the client configuration.
* It takes care of all "static" values like environment, release and `dist`,
* as well as truncating overly long values.
* @param event event instance to be enhanced
*/
BaseClient.prototype._applyClientOptions = function (event) {
var options = this.getOptions();
var environment = options.environment, release = options.release, dist = options.dist, _a = options.maxValueLength, maxValueLength = _a === void 0 ? 250 : _a;
if (!('environment' in event)) {
event.environment = 'environment' in options ? environment : 'production';
}
if (event.release === undefined && release !== undefined) {
event.release = release;
}
if (event.dist === undefined && dist !== undefined) {
event.dist = dist;
}
if (event.message) {
event.message = truncate(event.message, maxValueLength);
}
var exception = event.exception && event.exception.values && event.exception.values[0];
if (exception && exception.value) {
exception.value = truncate(exception.value, maxValueLength);
}
var request = event.request;
if (request && request.url) {
request.url = truncate(request.url, maxValueLength);
}
};
/**
* This function adds all used integrations to the SDK info in the event.
* @param sdkInfo The sdkInfo of the event that will be filled with all integrations.
*/
BaseClient.prototype._applyIntegrationsMetadata = function (event) {
var sdkInfo = event.sdk;
var integrationsArray = Object.keys(this._integrations);
if (sdkInfo && integrationsArray.length > 0) {
sdkInfo.integrations = integrationsArray;
}
};
/**
* Tells the backend to send this event
* @param event The Sentry event to send
*/
BaseClient.prototype._sendEvent = function (event) {
this._getBackend().sendEvent(event);
};
/**
* Processes the event and logs an error in case of rejection
* @param event
* @param hint
* @param scope
*/
BaseClient.prototype._captureEvent = function (event, hint, scope) {
return this._processEvent(event, hint, scope).then(function (finalEvent) {
return finalEvent.event_id;
}, function (reason) {
logger.error(reason);
return undefined;
});
};
/**
* Processes an event (either error or message) and sends it to Sentry.
*
* This also adds breadcrumbs and context information to the event. However,
* platform specific meta data (such as the User's IP address) must be added
* by the SDK implementor.
*
*
* @param event The event to send to Sentry.
* @param hint May contain additional information about the original exception.
* @param scope A scope containing event metadata.
* @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.
*/
BaseClient.prototype._processEvent = function (event, hint, scope) {
var _this = this;
// eslint-disable-next-line @typescript-eslint/unbound-method
var _a = this.getOptions(), beforeSend = _a.beforeSend, sampleRate = _a.sampleRate;
if (!this._isEnabled()) {
return syncpromise_SyncPromise.reject(new SentryError('SDK not enabled, will not send event.'));
}
var isTransaction = event.type === 'transaction';
// 1.0 === 100% events are sent
// 0.0 === 0% events are sent
// Sampling for transaction happens somewhere else
if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) {
return syncpromise_SyncPromise.reject(new SentryError("Discarding event because it's not included in the random sample (sampling rate = " + sampleRate + ")"));
}
return this._prepareEvent(event, scope, hint)
.then(function (prepared) {
if (prepared === null) {
throw new SentryError('An event processor returned null, will not send event.');
}
var isInternalException = hint && hint.data && hint.data.__sentry__ === true;
if (isInternalException || isTransaction || !beforeSend) {
return prepared;
}
var beforeSendResult = beforeSend(prepared, hint);
if (typeof beforeSendResult === 'undefined') {
throw new SentryError('`beforeSend` method has to return `null` or a valid event.');
}
else if (isThenable(beforeSendResult)) {
return beforeSendResult.then(function (event) { return event; }, function (e) {
throw new SentryError("beforeSend rejected with " + e);
});
}
return beforeSendResult;
})
.then(function (processedEvent) {
if (processedEvent === null) {
throw new SentryError('`beforeSend` returned `null`, will not send event.');
}
var session = scope && scope.getSession && scope.getSession();
if (!isTransaction && session) {
_this._updateSessionFromEvent(session, processedEvent);
}
_this._sendEvent(processedEvent);
return processedEvent;
})
.then(null, function (reason) {
if (reason instanceof SentryError) {
throw reason;
}
_this.captureException(reason, {
data: {
__sentry__: true,
},
originalException: reason,
});
throw new SentryError("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: " + reason);
});
};
/**
* Occupies the client with processing and event
*/
BaseClient.prototype._process = function (promise) {
var _this = this;
this._processing += 1;
promise.then(function (value) {
_this._processing -= 1;
return value;
}, function (reason) {
_this._processing -= 1;
return reason;
});
};
return BaseClient;
}());
//# sourceMappingURL=baseclient.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/types/esm/status.js
/** The status of an event. */
// eslint-disable-next-line import/export
var Status;
(function (Status) {
/** The status could not be determined. */
Status["Unknown"] = "unknown";
/** The event was skipped due to configuration or callbacks. */
Status["Skipped"] = "skipped";
/** The event was sent to Sentry successfully. */
Status["Success"] = "success";
/** The client is currently rate limited and will try again later. */
Status["RateLimit"] = "rate_limit";
/** The event could not be processed. */
Status["Invalid"] = "invalid";
/** A server-side error ocurred during submission. */
Status["Failed"] = "failed";
})(Status || (Status = {}));
// eslint-disable-next-line @typescript-eslint/no-namespace, import/export
(function (Status) {
/**
* Converts a HTTP status code into a {@link Status}.
*
* @param code The HTTP response status code.
* @returns The send status or {@link Status.Unknown}.
*/
function fromHttpCode(code) {
if (code >= 200 && code < 300) {
return Status.Success;
}
if (code === 429) {
return Status.RateLimit;
}
if (code >= 400 && code < 500) {
return Status.Invalid;
}
if (code >= 500) {
return Status.Failed;
}
return Status.Unknown;
}
Status.fromHttpCode = fromHttpCode;
})(Status || (Status = {}));
//# sourceMappingURL=status.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/core/esm/transports/noop.js
/** Noop transport */
var NoopTransport = /** @class */ (function () {
function NoopTransport() {
}
/**
* @inheritDoc
*/
NoopTransport.prototype.sendEvent = function (_) {
return syncpromise_SyncPromise.resolve({
reason: "NoopTransport: Event has been skipped because no Dsn is configured.",
status: Status.Skipped,
});
};
/**
* @inheritDoc
*/
NoopTransport.prototype.close = function (_) {
return syncpromise_SyncPromise.resolve(true);
};
return NoopTransport;
}());
//# sourceMappingURL=noop.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/core/esm/basebackend.js
/**
* This is the base implemention of a Backend.
* @hidden
*/
var BaseBackend = /** @class */ (function () {
/** Creates a new backend instance. */
function BaseBackend(options) {
this._options = options;
if (!this._options.dsn) {
logger.warn('No DSN provided, backend will not do anything.');
}
this._transport = this._setupTransport();
}
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
BaseBackend.prototype.eventFromException = function (_exception, _hint) {
throw new SentryError('Backend has to implement `eventFromException` method');
};
/**
* @inheritDoc
*/
BaseBackend.prototype.eventFromMessage = function (_message, _level, _hint) {
throw new SentryError('Backend has to implement `eventFromMessage` method');
};
/**
* @inheritDoc
*/
BaseBackend.prototype.sendEvent = function (event) {
this._transport.sendEvent(event).then(null, function (reason) {
logger.error("Error while sending event: " + reason);
});
};
/**
* @inheritDoc
*/
BaseBackend.prototype.sendSession = function (session) {
if (!this._transport.sendSession) {
logger.warn("Dropping session because custom transport doesn't implement sendSession");
return;
}
this._transport.sendSession(session).then(null, function (reason) {
logger.error("Error while sending session: " + reason);
});
};
/**
* @inheritDoc
*/
BaseBackend.prototype.getTransport = function () {
return this._transport;
};
/**
* Sets up the transport so it can be used later to send requests.
*/
BaseBackend.prototype._setupTransport = function () {
return new NoopTransport();
};
return BaseBackend;
}());
//# sourceMappingURL=basebackend.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/types/esm/severity.js
/** JSDoc */
// eslint-disable-next-line import/export
var Severity;
(function (Severity) {
/** JSDoc */
Severity["Fatal"] = "fatal";
/** JSDoc */
Severity["Error"] = "error";
/** JSDoc */
Severity["Warning"] = "warning";
/** JSDoc */
Severity["Log"] = "log";
/** JSDoc */
Severity["Info"] = "info";
/** JSDoc */
Severity["Debug"] = "debug";
/** JSDoc */
Severity["Critical"] = "critical";
})(Severity || (Severity = {}));
// eslint-disable-next-line @typescript-eslint/no-namespace, import/export
(function (Severity) {
/**
* Converts a string-based level into a {@link Severity}.
*
* @param level string representation of Severity
* @returns Severity
*/
function fromString(level) {
switch (level) {
case 'debug':
return Severity.Debug;
case 'info':
return Severity.Info;
case 'warn':
case 'warning':
return Severity.Warning;
case 'error':
return Severity.Error;
case 'fatal':
return Severity.Fatal;
case 'critical':
return Severity.Critical;
case 'log':
default:
return Severity.Log;
}
}
Severity.fromString = fromString;
})(Severity || (Severity = {}));
//# sourceMappingURL=severity.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/utils/esm/supports.js
/**
* Tells whether current environment supports ErrorEvent objects
* {@link supportsErrorEvent}.
*
* @returns Answer to the given question.
*/
function supportsErrorEvent() {
try {
new ErrorEvent('');
return true;
}
catch (e) {
return false;
}
}
/**
* Tells whether current environment supports DOMError objects
* {@link supportsDOMError}.
*
* @returns Answer to the given question.
*/
function supportsDOMError() {
try {
// Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':
// 1 argument required, but only 0 present.
// @ts-ignore It really needs 1 argument, not 0.
new DOMError('');
return true;
}
catch (e) {
return false;
}
}
/**
* Tells whether current environment supports DOMException objects
* {@link supportsDOMException}.
*
* @returns Answer to the given question.
*/
function supportsDOMException() {
try {
new DOMException('');
return true;
}
catch (e) {
return false;
}
}
/**
* Tells whether current environment supports Fetch API
* {@link supportsFetch}.
*
* @returns Answer to the given question.
*/
function supportsFetch() {
if (!('fetch' in (0,misc/* getGlobalObject */.Rf)())) {
return false;
}
try {
new Headers();
new Request('');
new Response();
return true;
}
catch (e) {
return false;
}
}
/**
* isNativeFetch checks if the given function is a native implementation of fetch()
*/
// eslint-disable-next-line @typescript-eslint/ban-types
function isNativeFetch(func) {
return func && /^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString());
}
/**
* Tells whether current environment supports Fetch API natively
* {@link supportsNativeFetch}.
*
* @returns true if `window.fetch` is natively implemented, false otherwise
*/
function supportsNativeFetch() {
if (!supportsFetch()) {
return false;
}
var global = (0,misc/* getGlobalObject */.Rf)();
// Fast path to avoid DOM I/O
// eslint-disable-next-line @typescript-eslint/unbound-method
if (isNativeFetch(global.fetch)) {
return true;
}
// window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)
// so create a "pure" iframe to see if that has native fetch
var result = false;
var doc = global.document;
// eslint-disable-next-line deprecation/deprecation
if (doc && typeof doc.createElement === "function") {
try {
var sandbox = doc.createElement('iframe');
sandbox.hidden = true;
doc.head.appendChild(sandbox);
if (sandbox.contentWindow && sandbox.contentWindow.fetch) {
// eslint-disable-next-line @typescript-eslint/unbound-method
result = isNativeFetch(sandbox.contentWindow.fetch);
}
doc.head.removeChild(sandbox);
}
catch (err) {
logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);
}
}
return result;
}
/**
* Tells whether current environment supports ReportingObserver API
* {@link supportsReportingObserver}.
*
* @returns Answer to the given question.
*/
function supportsReportingObserver() {
return 'ReportingObserver' in getGlobalObject();
}
/**
* Tells whether current environment supports Referrer Policy API
* {@link supportsReferrerPolicy}.
*
* @returns Answer to the given question.
*/
function supportsReferrerPolicy() {
// Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default
// https://caniuse.com/#feat=referrer-policy
// It doesn't. And it throw exception instead of ignoring this parameter...
// REF: https://github.com/getsentry/raven-js/issues/1233
if (!supportsFetch()) {
return false;
}
try {
new Request('_', {
referrerPolicy: 'origin',
});
return true;
}
catch (e) {
return false;
}
}
/**
* Tells whether current environment supports History API
* {@link supportsHistory}.
*
* @returns Answer to the given question.
*/
function supportsHistory() {
// NOTE: in Chrome App environment, touching history.pushState, *even inside
// a try/catch block*, will cause Chrome to output an error to console.error
// borrowed from: https://github.com/angular/angular.js/pull/13945/files
var global = (0,misc/* getGlobalObject */.Rf)();
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var chrome = global.chrome;
var isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;
/* eslint-enable @typescript-eslint/no-unsafe-member-access */
var hasHistoryApi = 'history' in global && !!global.history.pushState && !!global.history.replaceState;
return !isChromePackagedApp && hasHistoryApi;
}
//# sourceMappingURL=supports.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/tracekit.js
/**
* This was originally forked from https://github.com/occ/TraceKit, but has since been
* largely modified and is now maintained as part of Sentry JS SDK.
*/
// global reference to slice
var UNKNOWN_FUNCTION = '?';
// Chromium based browsers: Chrome, Brave, new Opera, new Edge
var tracekit_chrome = /^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|address|native|eval|webpack||[-a-z]+:|.*bundle|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
// gecko regex: `(?:bundle|\d+\.js)`: `bundle` is for react native, `\d+\.js` also but specifically for ram bundles because it
// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js
// We need this specific case for now because we want no other regex to match.
var gecko = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|capacitor).*?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
var winjs = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
var geckoEval = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
var chromeEval = /\((\S*)(?::(\d+))(?::(\d+))\)/;
// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108
var reactMinifiedRegexp = /Minified React error #\d+;/i;
/** JSDoc */
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
function computeStackTrace(ex) {
var stack = null;
var popSize = 0;
if (ex) {
if (typeof ex.framesToPop === 'number') {
popSize = ex.framesToPop;
}
else if (reactMinifiedRegexp.test(ex.message)) {
popSize = 1;
}
}
try {
// This must be tried first because Opera 10 *destroys*
// its stacktrace property if you try to access the stack
// property first!!
stack = computeStackTraceFromStacktraceProp(ex);
if (stack) {
return popFrames(stack, popSize);
}
}
catch (e) {
// no-empty
}
try {
stack = computeStackTraceFromStackProp(ex);
if (stack) {
return popFrames(stack, popSize);
}
}
catch (e) {
// no-empty
}
return {
message: extractMessage(ex),
name: ex && ex.name,
stack: [],
failed: true,
};
}
/** JSDoc */
// eslint-disable-next-line @typescript-eslint/no-explicit-any, complexity
function computeStackTraceFromStackProp(ex) {
if (!ex || !ex.stack) {
return null;
}
var stack = [];
var lines = ex.stack.split('\n');
var isEval;
var submatch;
var parts;
var element;
for (var i = 0; i < lines.length; ++i) {
if ((parts = tracekit_chrome.exec(lines[i]))) {
var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line
isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line
if (isEval && (submatch = chromeEval.exec(parts[2]))) {
// throw out eval line/column and use top-most line/column number
parts[2] = submatch[1]; // url
parts[3] = submatch[2]; // line
parts[4] = submatch[3]; // column
}
element = {
// working with the regexp above is super painful. it is quite a hack, but just stripping the `address at `
// prefix here seems like the quickest solution for now.
url: parts[2] && parts[2].indexOf('address at ') === 0 ? parts[2].substr('address at '.length) : parts[2],
func: parts[1] || UNKNOWN_FUNCTION,
args: isNative ? [parts[2]] : [],
line: parts[3] ? +parts[3] : null,
column: parts[4] ? +parts[4] : null,
};
}
else if ((parts = winjs.exec(lines[i]))) {
element = {
url: parts[2],
func: parts[1] || UNKNOWN_FUNCTION,
args: [],
line: +parts[3],
column: parts[4] ? +parts[4] : null,
};
}
else if ((parts = gecko.exec(lines[i]))) {
isEval = parts[3] && parts[3].indexOf(' > eval') > -1;
if (isEval && (submatch = geckoEval.exec(parts[3]))) {
// throw out eval line/column and use top-most line number
parts[1] = parts[1] || "eval";
parts[3] = submatch[1];
parts[4] = submatch[2];
parts[5] = ''; // no column when eval
}
else if (i === 0 && !parts[5] && ex.columnNumber !== void 0) {
// FireFox uses this awesome columnNumber property for its top frame
// Also note, Firefox's column number is 0-based and everything else expects 1-based,
// so adding 1
// NOTE: this hack doesn't work if top-most frame is eval
stack[0].column = ex.columnNumber + 1;
}
element = {
url: parts[3],
func: parts[1] || UNKNOWN_FUNCTION,
args: parts[2] ? parts[2].split(',') : [],
line: parts[4] ? +parts[4] : null,
column: parts[5] ? +parts[5] : null,
};
}
else {
continue;
}
if (!element.func && element.line) {
element.func = UNKNOWN_FUNCTION;
}
stack.push(element);
}
if (!stack.length) {
return null;
}
return {
message: extractMessage(ex),
name: ex.name,
stack: stack,
};
}
/** JSDoc */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function computeStackTraceFromStacktraceProp(ex) {
if (!ex || !ex.stacktrace) {
return null;
}
// Access and store the stacktrace property before doing ANYTHING
// else to it because Opera is not very good at providing it
// reliably in other circumstances.
var stacktrace = ex.stacktrace;
var opera10Regex = / line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i;
var opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:]+)>|([^)]+))\((.*)\))? in (.*):\s*$/i;
var lines = stacktrace.split('\n');
var stack = [];
var parts;
for (var line = 0; line < lines.length; line += 2) {
var element = null;
if ((parts = opera10Regex.exec(lines[line]))) {
element = {
url: parts[2],
func: parts[3],
args: [],
line: +parts[1],
column: null,
};
}
else if ((parts = opera11Regex.exec(lines[line]))) {
element = {
url: parts[6],
func: parts[3] || parts[4],
args: parts[5] ? parts[5].split(',') : [],
line: +parts[1],
column: +parts[2],
};
}
if (element) {
if (!element.func && element.line) {
element.func = UNKNOWN_FUNCTION;
}
stack.push(element);
}
}
if (!stack.length) {
return null;
}
return {
message: extractMessage(ex),
name: ex.name,
stack: stack,
};
}
/** Remove N number of frames from the stack */
function popFrames(stacktrace, popSize) {
try {
return tslib_es6_assign(tslib_es6_assign({}, stacktrace), { stack: stacktrace.stack.slice(popSize) });
}
catch (e) {
return stacktrace;
}
}
/**
* There are cases where stacktrace.message is an Event object
* https://github.com/getsentry/sentry-javascript/issues/1949
* In this specific case we try to extract stacktrace.message.error.message
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function extractMessage(ex) {
var message = ex && ex.message;
if (!message) {
return 'No error message';
}
if (message.error && typeof message.error.message === 'string') {
return message.error.message;
}
return message;
}
//# sourceMappingURL=tracekit.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/parsers.js
var STACKTRACE_LIMIT = 50;
/**
* This function creates an exception from an TraceKitStackTrace
* @param stacktrace TraceKitStackTrace that will be converted to an exception
* @hidden
*/
function exceptionFromStacktrace(stacktrace) {
var frames = prepareFramesForEvent(stacktrace.stack);
var exception = {
type: stacktrace.name,
value: stacktrace.message,
};
if (frames && frames.length) {
exception.stacktrace = { frames: frames };
}
if (exception.type === undefined && exception.value === '') {
exception.value = 'Unrecoverable error caught';
}
return exception;
}
/**
* @hidden
*/
function eventFromPlainObject(exception, syntheticException, rejection) {
var event = {
exception: {
values: [
{
type: isEvent(exception) ? exception.constructor.name : rejection ? 'UnhandledRejection' : 'Error',
value: "Non-Error " + (rejection ? 'promise rejection' : 'exception') + " captured with keys: " + extractExceptionKeysForMessage(exception),
},
],
},
extra: {
__serialized__: normalizeToSize(exception),
},
};
if (syntheticException) {
var stacktrace = computeStackTrace(syntheticException);
var frames_1 = prepareFramesForEvent(stacktrace.stack);
event.stacktrace = {
frames: frames_1,
};
}
return event;
}
/**
* @hidden
*/
function eventFromStacktrace(stacktrace) {
var exception = exceptionFromStacktrace(stacktrace);
return {
exception: {
values: [exception],
},
};
}
/**
* @hidden
*/
function prepareFramesForEvent(stack) {
if (!stack || !stack.length) {
return [];
}
var localStack = stack;
var firstFrameFunction = localStack[0].func || '';
var lastFrameFunction = localStack[localStack.length - 1].func || '';
// If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)
if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) {
localStack = localStack.slice(1);
}
// If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)
if (lastFrameFunction.indexOf('sentryWrapped') !== -1) {
localStack = localStack.slice(0, -1);
}
// The frame where the crash happened, should be the last entry in the array
return localStack
.slice(0, STACKTRACE_LIMIT)
.map(function (frame) { return ({
colno: frame.column === null ? undefined : frame.column,
filename: frame.url || localStack[0].url,
function: frame.func || '?',
in_app: true,
lineno: frame.line === null ? undefined : frame.line,
}); })
.reverse();
}
//# sourceMappingURL=parsers.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/eventbuilder.js
/**
* Builds and Event from a Exception
* @hidden
*/
function eventFromException(options, exception, hint) {
var syntheticException = (hint && hint.syntheticException) || undefined;
var event = eventFromUnknownInput(exception, syntheticException, {
attachStacktrace: options.attachStacktrace,
});
(0,misc/* addExceptionMechanism */.EG)(event, {
handled: true,
type: 'generic',
});
event.level = Severity.Error;
if (hint && hint.event_id) {
event.event_id = hint.event_id;
}
return syncpromise_SyncPromise.resolve(event);
}
/**
* Builds and Event from a Message
* @hidden
*/
function eventFromMessage(options, message, level, hint) {
if (level === void 0) { level = Severity.Info; }
var syntheticException = (hint && hint.syntheticException) || undefined;
var event = eventFromString(message, syntheticException, {
attachStacktrace: options.attachStacktrace,
});
event.level = level;
if (hint && hint.event_id) {
event.event_id = hint.event_id;
}
return syncpromise_SyncPromise.resolve(event);
}
/**
* @hidden
*/
function eventFromUnknownInput(exception, syntheticException, options) {
if (options === void 0) { options = {}; }
var event;
if (isErrorEvent(exception) && exception.error) {
// If it is an ErrorEvent with `error` property, extract it to get actual Error
var errorEvent = exception;
// eslint-disable-next-line no-param-reassign
exception = errorEvent.error;
event = eventFromStacktrace(computeStackTrace(exception));
return event;
}
if (isDOMError(exception) || isDOMException(exception)) {
// If it is a DOMError or DOMException (which are legacy APIs, but still supported in some browsers)
// then we just extract the name, code, and message, as they don't provide anything else
// https://developer.mozilla.org/en-US/docs/Web/API/DOMError
// https://developer.mozilla.org/en-US/docs/Web/API/DOMException
var domException = exception;
var name_1 = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');
var message = domException.message ? name_1 + ": " + domException.message : name_1;
event = eventFromString(message, syntheticException, options);
(0,misc/* addExceptionTypeValue */.Db)(event, message);
if ('code' in domException) {
event.tags = tslib_es6_assign(tslib_es6_assign({}, event.tags), { 'DOMException.code': "" + domException.code });
}
return event;
}
if (isError(exception)) {
// we have a real Error object, do nothing
event = eventFromStacktrace(computeStackTrace(exception));
return event;
}
if (isPlainObject(exception) || isEvent(exception)) {
// If it is plain Object or Event, serialize it manually and extract options
// This will allow us to group events based on top-level keys
// which is much better than creating new group when any key/value change
var objectException = exception;
event = eventFromPlainObject(objectException, syntheticException, options.rejection);
(0,misc/* addExceptionMechanism */.EG)(event, {
synthetic: true,
});
return event;
}
// If none of previous checks were valid, then it means that it's not:
// - an instance of DOMError
// - an instance of DOMException
// - an instance of Event
// - an instance of Error
// - a valid ErrorEvent (one with an error property)
// - a plain Object
//
// So bail out and capture it as a simple message:
event = eventFromString(exception, syntheticException, options);
(0,misc/* addExceptionTypeValue */.Db)(event, "" + exception, undefined);
(0,misc/* addExceptionMechanism */.EG)(event, {
synthetic: true,
});
return event;
}
/**
* @hidden
*/
function eventFromString(input, syntheticException, options) {
if (options === void 0) { options = {}; }
var event = {
message: input,
};
if (options.attachStacktrace && syntheticException) {
var stacktrace = computeStackTrace(syntheticException);
var frames_1 = prepareFramesForEvent(stacktrace.stack);
event.stacktrace = {
frames: frames_1,
};
}
return event;
}
//# sourceMappingURL=eventbuilder.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/core/esm/request.js
/** Creates a SentryRequest from an event. */
function sessionToSentryRequest(session, api) {
var envelopeHeaders = JSON.stringify({
sent_at: new Date().toISOString(),
});
var itemHeaders = JSON.stringify({
type: 'session',
});
return {
body: envelopeHeaders + "\n" + itemHeaders + "\n" + JSON.stringify(session),
type: 'session',
url: api.getEnvelopeEndpointWithUrlEncodedAuth(),
};
}
/** Creates a SentryRequest from an event. */
function eventToSentryRequest(event, api) {
// since JS has no Object.prototype.pop()
var _a = event.tags || {}, samplingMethod = _a.__sentry_samplingMethod, sampleRate = _a.__sentry_sampleRate, otherTags = __rest(_a, ["__sentry_samplingMethod", "__sentry_sampleRate"]);
event.tags = otherTags;
var useEnvelope = event.type === 'transaction';
var req = {
body: JSON.stringify(event),
type: event.type || 'event',
url: useEnvelope ? api.getEnvelopeEndpointWithUrlEncodedAuth() : api.getStoreEndpointWithUrlEncodedAuth(),
};
// https://develop.sentry.dev/sdk/envelopes/
// Since we don't need to manipulate envelopes nor store them, there is no
// exported concept of an Envelope with operations including serialization and
// deserialization. Instead, we only implement a minimal subset of the spec to
// serialize events inline here.
if (useEnvelope) {
var envelopeHeaders = JSON.stringify({
event_id: event.event_id,
sent_at: new Date().toISOString(),
});
var itemHeaders = JSON.stringify({
type: event.type,
// TODO: Right now, sampleRate may or may not be defined (it won't be in the cases of inheritance and
// explicitly-set sampling decisions). Are we good with that?
sample_rates: [{ id: samplingMethod, rate: sampleRate }],
});
// The trailing newline is optional. We intentionally don't send it to avoid
// sending unnecessary bytes.
//
// const envelope = `${envelopeHeaders}\n${itemHeaders}\n${req.body}\n`;
var envelope = envelopeHeaders + "\n" + itemHeaders + "\n" + req.body;
req.body = envelope;
}
return req;
}
//# sourceMappingURL=request.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/core/esm/api.js
var SENTRY_API_VERSION = '7';
/** Helper class to provide urls to different Sentry endpoints. */
var API = /** @class */ (function () {
/** Create a new instance of API */
function API(dsn) {
this.dsn = dsn;
this._dsnObject = new Dsn(dsn);
}
/** Returns the Dsn object. */
API.prototype.getDsn = function () {
return this._dsnObject;
};
/** Returns the prefix to construct Sentry ingestion API endpoints. */
API.prototype.getBaseApiEndpoint = function () {
var dsn = this._dsnObject;
var protocol = dsn.protocol ? dsn.protocol + ":" : '';
var port = dsn.port ? ":" + dsn.port : '';
return protocol + "//" + dsn.host + port + (dsn.path ? "/" + dsn.path : '') + "/api/";
};
/** Returns the store endpoint URL. */
API.prototype.getStoreEndpoint = function () {
return this._getIngestEndpoint('store');
};
/**
* Returns the store endpoint URL with auth in the query string.
*
* Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.
*/
API.prototype.getStoreEndpointWithUrlEncodedAuth = function () {
return this.getStoreEndpoint() + "?" + this._encodedAuth();
};
/**
* Returns the envelope endpoint URL with auth in the query string.
*
* Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.
*/
API.prototype.getEnvelopeEndpointWithUrlEncodedAuth = function () {
return this._getEnvelopeEndpoint() + "?" + this._encodedAuth();
};
/** Returns only the path component for the store endpoint. */
API.prototype.getStoreEndpointPath = function () {
var dsn = this._dsnObject;
return (dsn.path ? "/" + dsn.path : '') + "/api/" + dsn.projectId + "/store/";
};
/**
* Returns an object that can be used in request headers.
* This is needed for node and the old /store endpoint in sentry
*/
API.prototype.getRequestHeaders = function (clientName, clientVersion) {
var dsn = this._dsnObject;
var header = ["Sentry sentry_version=" + SENTRY_API_VERSION];
header.push("sentry_client=" + clientName + "/" + clientVersion);
header.push("sentry_key=" + dsn.user);
if (dsn.pass) {
header.push("sentry_secret=" + dsn.pass);
}
return {
'Content-Type': 'application/json',
'X-Sentry-Auth': header.join(', '),
};
};
/** Returns the url to the report dialog endpoint. */
API.prototype.getReportDialogEndpoint = function (dialogOptions) {
if (dialogOptions === void 0) { dialogOptions = {}; }
var dsn = this._dsnObject;
var endpoint = this.getBaseApiEndpoint() + "embed/error-page/";
var encodedOptions = [];
encodedOptions.push("dsn=" + dsn.toString());
for (var key in dialogOptions) {
if (key === 'dsn') {
continue;
}
if (key === 'user') {
if (!dialogOptions.user) {
continue;
}
if (dialogOptions.user.name) {
encodedOptions.push("name=" + encodeURIComponent(dialogOptions.user.name));
}
if (dialogOptions.user.email) {
encodedOptions.push("email=" + encodeURIComponent(dialogOptions.user.email));
}
}
else {
encodedOptions.push(encodeURIComponent(key) + "=" + encodeURIComponent(dialogOptions[key]));
}
}
if (encodedOptions.length) {
return endpoint + "?" + encodedOptions.join('&');
}
return endpoint;
};
/** Returns the envelope endpoint URL. */
API.prototype._getEnvelopeEndpoint = function () {
return this._getIngestEndpoint('envelope');
};
/** Returns the ingest API endpoint for target. */
API.prototype._getIngestEndpoint = function (target) {
var base = this.getBaseApiEndpoint();
var dsn = this._dsnObject;
return "" + base + dsn.projectId + "/" + target + "/";
};
/** Returns a URL-encoded string with auth config suitable for a query string. */
API.prototype._encodedAuth = function () {
var dsn = this._dsnObject;
var auth = {
// We send only the minimum set of required information. See
// https://github.com/getsentry/sentry-javascript/issues/2572.
sentry_key: dsn.user,
sentry_version: SENTRY_API_VERSION,
};
return urlEncode(auth);
};
return API;
}());
//# sourceMappingURL=api.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/utils/esm/promisebuffer.js
/** A simple queue that holds promises. */
var PromiseBuffer = /** @class */ (function () {
function PromiseBuffer(_limit) {
this._limit = _limit;
/** Internal set of queued Promises */
this._buffer = [];
}
/**
* Says if the buffer is ready to take more requests
*/
PromiseBuffer.prototype.isReady = function () {
return this._limit === undefined || this.length() < this._limit;
};
/**
* Add a promise to the queue.
*
* @param task Can be any PromiseLike
* @returns The original promise.
*/
PromiseBuffer.prototype.add = function (task) {
var _this = this;
if (!this.isReady()) {
return syncpromise_SyncPromise.reject(new SentryError('Not adding Promise due to buffer limit reached.'));
}
if (this._buffer.indexOf(task) === -1) {
this._buffer.push(task);
}
task
.then(function () { return _this.remove(task); })
.then(null, function () {
return _this.remove(task).then(null, function () {
// We have to add this catch here otherwise we have an unhandledPromiseRejection
// because it's a new Promise chain.
});
});
return task;
};
/**
* Remove a promise to the queue.
*
* @param task Can be any PromiseLike
* @returns Removed promise.
*/
PromiseBuffer.prototype.remove = function (task) {
var removedTask = this._buffer.splice(this._buffer.indexOf(task), 1)[0];
return removedTask;
};
/**
* This function returns the number of unresolved promises in the queue.
*/
PromiseBuffer.prototype.length = function () {
return this._buffer.length;
};
/**
* This will drain the whole queue, returns true if queue is empty or drained.
* If timeout is provided and the queue takes longer to drain, the promise still resolves but with false.
*
* @param timeout Number in ms to wait until it resolves with false.
*/
PromiseBuffer.prototype.drain = function (timeout) {
var _this = this;
return new syncpromise_SyncPromise(function (resolve) {
var capturedSetTimeout = setTimeout(function () {
if (timeout && timeout > 0) {
resolve(false);
}
}, timeout);
syncpromise_SyncPromise.all(_this._buffer)
.then(function () {
clearTimeout(capturedSetTimeout);
resolve(true);
})
.then(null, function () {
resolve(true);
});
});
};
return PromiseBuffer;
}());
//# sourceMappingURL=promisebuffer.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/transports/base.js
/** Base Transport class implementation */
var BaseTransport = /** @class */ (function () {
function BaseTransport(options) {
this.options = options;
/** A simple buffer holding all requests. */
this._buffer = new PromiseBuffer(30);
/** Locks transport after receiving rate limits in a response */
this._rateLimits = {};
this._api = new API(this.options.dsn);
// eslint-disable-next-line deprecation/deprecation
this.url = this._api.getStoreEndpointWithUrlEncodedAuth();
}
/**
* @inheritDoc
*/
BaseTransport.prototype.sendEvent = function (_) {
throw new SentryError('Transport Class has to implement `sendEvent` method');
};
/**
* @inheritDoc
*/
BaseTransport.prototype.close = function (timeout) {
return this._buffer.drain(timeout);
};
/**
* Handle Sentry repsonse for promise-based transports.
*/
BaseTransport.prototype._handleResponse = function (_a) {
var requestType = _a.requestType, response = _a.response, headers = _a.headers, resolve = _a.resolve, reject = _a.reject;
var status = Status.fromHttpCode(response.status);
/**
* "The name is case-insensitive."
* https://developer.mozilla.org/en-US/docs/Web/API/Headers/get
*/
var limited = this._handleRateLimit(headers);
if (limited)
logger.warn("Too many requests, backing off until: " + this._disabledUntil(requestType));
if (status === Status.Success) {
resolve({ status: status });
return;
}
reject(response);
};
/**
* Gets the time that given category is disabled until for rate limiting
*/
BaseTransport.prototype._disabledUntil = function (category) {
return this._rateLimits[category] || this._rateLimits.all;
};
/**
* Checks if a category is rate limited
*/
BaseTransport.prototype._isRateLimited = function (category) {
return this._disabledUntil(category) > new Date(Date.now());
};
/**
* Sets internal _rateLimits from incoming headers. Returns true if headers contains a non-empty rate limiting header.
*/
BaseTransport.prototype._handleRateLimit = function (headers) {
var e_1, _a, e_2, _b;
var now = Date.now();
var rlHeader = headers['x-sentry-rate-limits'];
var raHeader = headers['retry-after'];
if (rlHeader) {
try {
// rate limit headers are of the form
// ,,..
// where each is of the form
// : : :
// where
// is a delay in ms
// is the event type(s) (error, transaction, etc) being rate limited and is of the form
// ;;...
// is what's being limited (org, project, or key) - ignored by SDK
// is an arbitrary string like "org_quota" - ignored by SDK
for (var _c = __values(rlHeader.trim().split(',')), _d = _c.next(); !_d.done; _d = _c.next()) {
var limit = _d.value;
var parameters = limit.split(':', 2);
var headerDelay = parseInt(parameters[0], 10);
var delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default
try {
for (var _e = (e_2 = void 0, __values(parameters[1].split(';'))), _f = _e.next(); !_f.done; _f = _e.next()) {
var category = _f.value;
this._rateLimits[category || 'all'] = new Date(now + delay);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
}
finally { if (e_2) throw e_2.error; }
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_1) throw e_1.error; }
}
return true;
}
else if (raHeader) {
this._rateLimits.all = new Date(now + (0,misc/* parseRetryAfterHeader */.JY)(now, raHeader));
return true;
}
return false;
};
return BaseTransport;
}());
//# sourceMappingURL=base.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/transports/fetch.js
var fetch_global = (0,misc/* getGlobalObject */.Rf)();
/** `fetch` based transport */
var FetchTransport = /** @class */ (function (_super) {
__extends(FetchTransport, _super);
function FetchTransport() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @inheritDoc
*/
FetchTransport.prototype.sendEvent = function (event) {
return this._sendRequest(eventToSentryRequest(event, this._api), event);
};
/**
* @inheritDoc
*/
FetchTransport.prototype.sendSession = function (session) {
return this._sendRequest(sessionToSentryRequest(session, this._api), session);
};
/**
* @param sentryRequest Prepared SentryRequest to be delivered
* @param originalPayload Original payload used to create SentryRequest
*/
FetchTransport.prototype._sendRequest = function (sentryRequest, originalPayload) {
var _this = this;
if (this._isRateLimited(sentryRequest.type)) {
return Promise.reject({
event: originalPayload,
type: sentryRequest.type,
reason: "Transport locked till " + this._disabledUntil(sentryRequest.type) + " due to too many requests.",
status: 429,
});
}
var options = {
body: sentryRequest.body,
method: 'POST',
// Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default
// https://caniuse.com/#feat=referrer-policy
// It doesn't. And it throw exception instead of ignoring this parameter...
// REF: https://github.com/getsentry/raven-js/issues/1233
referrerPolicy: (supportsReferrerPolicy() ? 'origin' : ''),
};
if (this.options.fetchParameters !== undefined) {
Object.assign(options, this.options.fetchParameters);
}
if (this.options.headers !== undefined) {
options.headers = this.options.headers;
}
return this._buffer.add(new syncpromise_SyncPromise(function (resolve, reject) {
fetch_global
.fetch(sentryRequest.url, options)
.then(function (response) {
var headers = {
'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),
'retry-after': response.headers.get('Retry-After'),
};
_this._handleResponse({
requestType: sentryRequest.type,
response: response,
headers: headers,
resolve: resolve,
reject: reject,
});
})
.catch(reject);
}));
};
return FetchTransport;
}(BaseTransport));
//# sourceMappingURL=fetch.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/transports/xhr.js
/** `XHR` based transport */
var XHRTransport = /** @class */ (function (_super) {
__extends(XHRTransport, _super);
function XHRTransport() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @inheritDoc
*/
XHRTransport.prototype.sendEvent = function (event) {
return this._sendRequest(eventToSentryRequest(event, this._api), event);
};
/**
* @inheritDoc
*/
XHRTransport.prototype.sendSession = function (session) {
return this._sendRequest(sessionToSentryRequest(session, this._api), session);
};
/**
* @param sentryRequest Prepared SentryRequest to be delivered
* @param originalPayload Original payload used to create SentryRequest
*/
XHRTransport.prototype._sendRequest = function (sentryRequest, originalPayload) {
var _this = this;
if (this._isRateLimited(sentryRequest.type)) {
return Promise.reject({
event: originalPayload,
type: sentryRequest.type,
reason: "Transport locked till " + this._disabledUntil(sentryRequest.type) + " due to too many requests.",
status: 429,
});
}
return this._buffer.add(new syncpromise_SyncPromise(function (resolve, reject) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
var headers = {
'x-sentry-rate-limits': request.getResponseHeader('X-Sentry-Rate-Limits'),
'retry-after': request.getResponseHeader('Retry-After'),
};
_this._handleResponse({ requestType: sentryRequest.type, response: request, headers: headers, resolve: resolve, reject: reject });
}
};
request.open('POST', sentryRequest.url);
for (var header in _this.options.headers) {
if (_this.options.headers.hasOwnProperty(header)) {
request.setRequestHeader(header, _this.options.headers[header]);
}
}
request.send(sentryRequest.body);
}));
};
return XHRTransport;
}(BaseTransport));
//# sourceMappingURL=xhr.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/backend.js
/**
* The Sentry Browser SDK Backend.
* @hidden
*/
var BrowserBackend = /** @class */ (function (_super) {
__extends(BrowserBackend, _super);
function BrowserBackend() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @inheritDoc
*/
BrowserBackend.prototype.eventFromException = function (exception, hint) {
return eventFromException(this._options, exception, hint);
};
/**
* @inheritDoc
*/
BrowserBackend.prototype.eventFromMessage = function (message, level, hint) {
if (level === void 0) { level = Severity.Info; }
return eventFromMessage(this._options, message, level, hint);
};
/**
* @inheritDoc
*/
BrowserBackend.prototype._setupTransport = function () {
if (!this._options.dsn) {
// We return the noop transport here in case there is no Dsn.
return _super.prototype._setupTransport.call(this);
}
var transportOptions = tslib_es6_assign(tslib_es6_assign({}, this._options.transportOptions), { dsn: this._options.dsn });
if (this._options.transport) {
return new this._options.transport(transportOptions);
}
if (supportsFetch()) {
return new FetchTransport(transportOptions);
}
return new XHRTransport(transportOptions);
};
return BrowserBackend;
}(BaseBackend));
//# sourceMappingURL=backend.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/minimal/esm/index.js
/**
* This calls a function on the current hub.
* @param method function to call on hub.
* @param args to pass to function.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function callOnHub(method) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
var hub = hub_getCurrentHub();
if (hub && hub[method]) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return hub[method].apply(hub, tslib_es6_spread(args));
}
throw new Error("No hub defined or " + method + " was not found on the hub, please open a bug report.");
}
/**
* Captures an exception event and sends it to Sentry.
*
* @param exception An exception-like object.
* @returns The generated eventId.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
function captureException(exception, captureContext) {
var syntheticException;
try {
throw new Error('Sentry syntheticException');
}
catch (exception) {
syntheticException = exception;
}
return callOnHub('captureException', exception, {
captureContext: captureContext,
originalException: exception,
syntheticException: syntheticException,
});
}
/**
* Captures a message event and sends it to Sentry.
*
* @param message The message to send to Sentry.
* @param level Define the level of the message.
* @returns The generated eventId.
*/
function captureMessage(message, captureContext) {
var syntheticException;
try {
throw new Error(message);
}
catch (exception) {
syntheticException = exception;
}
// This is necessary to provide explicit scopes upgrade, without changing the original
// arity of the `captureMessage(message, level)` method.
var level = typeof captureContext === 'string' ? captureContext : undefined;
var context = typeof captureContext !== 'string' ? { captureContext: captureContext } : undefined;
return callOnHub('captureMessage', message, level, __assign({ originalException: message, syntheticException: syntheticException }, context));
}
/**
* Captures a manually created event and sends it to Sentry.
*
* @param event The event to send to Sentry.
* @returns The generated eventId.
*/
function captureEvent(event) {
return callOnHub('captureEvent', event);
}
/**
* Callback to set context information onto the scope.
* @param callback Callback function that receives Scope.
*/
function configureScope(callback) {
callOnHub('configureScope', callback);
}
/**
* Records a new breadcrumb which will be attached to future events.
*
* Breadcrumbs will be added to subsequent events to provide more context on
* user's actions prior to an error or crash.
*
* @param breadcrumb The breadcrumb to record.
*/
function addBreadcrumb(breadcrumb) {
callOnHub('addBreadcrumb', breadcrumb);
}
/**
* Sets context data with the given name.
* @param name of the context
* @param context Any kind of data. This data will be normalized.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function setContext(name, context) {
callOnHub('setContext', name, context);
}
/**
* Set an object that will be merged sent as extra data with the event.
* @param extras Extras object to merge into current context.
*/
function setExtras(extras) {
callOnHub('setExtras', extras);
}
/**
* Set an object that will be merged sent as tags data with the event.
* @param tags Tags context object to merge into current context.
*/
function setTags(tags) {
callOnHub('setTags', tags);
}
/**
* Set key:value that will be sent as extra data with the event.
* @param key String of extra
* @param extra Any kind of data. This data will be normalized.
*/
function setExtra(key, extra) {
callOnHub('setExtra', key, extra);
}
/**
* Set key:value that will be sent as tags data with the event.
*
* Can also be used to unset a tag, by passing `undefined`.
*
* @param key String key of tag
* @param value Value of tag
*/
function setTag(key, value) {
callOnHub('setTag', key, value);
}
/**
* Updates user context information for future events.
*
* @param user User context object to be set in the current context. Pass `null` to unset the user.
*/
function setUser(user) {
callOnHub('setUser', user);
}
/**
* Creates a new scope with and executes the given operation within.
* The scope is automatically removed once the operation
* finishes or throws.
*
* This is essentially a convenience function for:
*
* pushScope();
* callback();
* popScope();
*
* @param callback that will be enclosed into push/popScope.
*/
function withScope(callback) {
callOnHub('withScope', callback);
}
/**
* Calls a function on the latest client. Use this with caution, it's meant as
* in "internal" helper so we don't need to expose every possible function in
* the shim. It is not guaranteed that the client actually implements the
* function.
*
* @param method The method to call on the client/client.
* @param args Arguments to pass to the client/fontend.
* @hidden
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function _callOnClient(method) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
callOnHub.apply(void 0, __spread(['_invokeClient', method], args));
}
/**
* Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.
*
* A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a
* new child span within the transaction or any span, call the respective `.startChild()` method.
*
* Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.
*
* The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its
* finished child spans will be sent to Sentry.
*
* @param context Properties of the new `Transaction`.
* @param customSamplingContext Information given to the transaction sampling function (along with context-dependent
* default values). See {@link Options.tracesSampler}.
*
* @returns The transaction which was just started
*/
function startTransaction(context, customSamplingContext) {
return callOnHub('startTransaction', __assign({}, context), customSamplingContext);
}
//# sourceMappingURL=index.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/helpers.js
var ignoreOnError = 0;
/**
* @hidden
*/
function shouldIgnoreOnError() {
return ignoreOnError > 0;
}
/**
* @hidden
*/
function ignoreNextOnError() {
// onerror should trigger before setTimeout
ignoreOnError += 1;
setTimeout(function () {
ignoreOnError -= 1;
});
}
/**
* Instruments the given function and sends an event to Sentry every time the
* function throws an exception.
*
* @param fn A function to wrap.
* @returns The wrapped function.
* @hidden
*/
function wrap(fn, options, before) {
if (options === void 0) { options = {}; }
if (typeof fn !== 'function') {
return fn;
}
try {
// We don't wanna wrap it twice
if (fn.__sentry__) {
return fn;
}
// If this has already been wrapped in the past, return that wrapped function
if (fn.__sentry_wrapped__) {
return fn.__sentry_wrapped__;
}
}
catch (e) {
// Just accessing custom props in some Selenium environments
// can cause a "Permission denied" exception (see raven-js#495).
// Bail on wrapping and return the function as-is (defers to window.onerror).
return fn;
}
/* eslint-disable prefer-rest-params */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var sentryWrapped = function () {
var args = Array.prototype.slice.call(arguments);
try {
if (before && typeof before === 'function') {
before.apply(this, arguments);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
var wrappedArguments = args.map(function (arg) { return wrap(arg, options); });
if (fn.handleEvent) {
// Attempt to invoke user-land function
// NOTE: If you are a Sentry user, and you are seeing this stack frame, it
// means the sentry.javascript SDK caught an error invoking your application code. This
// is expected behavior and NOT indicative of a bug with sentry.javascript.
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return fn.handleEvent.apply(this, wrappedArguments);
}
// Attempt to invoke user-land function
// NOTE: If you are a Sentry user, and you are seeing this stack frame, it
// means the sentry.javascript SDK caught an error invoking your application code. This
// is expected behavior and NOT indicative of a bug with sentry.javascript.
return fn.apply(this, wrappedArguments);
}
catch (ex) {
ignoreNextOnError();
withScope(function (scope) {
scope.addEventProcessor(function (event) {
var processedEvent = tslib_es6_assign({}, event);
if (options.mechanism) {
(0,misc/* addExceptionTypeValue */.Db)(processedEvent, undefined, undefined);
(0,misc/* addExceptionMechanism */.EG)(processedEvent, options.mechanism);
}
processedEvent.extra = tslib_es6_assign(tslib_es6_assign({}, processedEvent.extra), { arguments: args });
return processedEvent;
});
captureException(ex);
});
throw ex;
}
};
/* eslint-enable prefer-rest-params */
// Accessing some objects may throw
// ref: https://github.com/getsentry/sentry-javascript/issues/1168
try {
for (var property in fn) {
if (Object.prototype.hasOwnProperty.call(fn, property)) {
sentryWrapped[property] = fn[property];
}
}
}
catch (_oO) { } // eslint-disable-line no-empty
fn.prototype = fn.prototype || {};
sentryWrapped.prototype = fn.prototype;
Object.defineProperty(fn, '__sentry_wrapped__', {
enumerable: false,
value: sentryWrapped,
});
// Signal that this function has been wrapped/filled already
// for both debugging and to prevent it to being wrapped/filled twice
Object.defineProperties(sentryWrapped, {
__sentry__: {
enumerable: false,
value: true,
},
__sentry_original__: {
enumerable: false,
value: fn,
},
});
// Restore original function name (not all browsers allow that)
try {
var descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name');
if (descriptor.configurable) {
Object.defineProperty(sentryWrapped, 'name', {
get: function () {
return fn.name;
},
});
}
// eslint-disable-next-line no-empty
}
catch (_oO) { }
return sentryWrapped;
}
/**
* Injects the Report Dialog script
* @hidden
*/
function injectReportDialog(options) {
if (options === void 0) { options = {}; }
if (!options.eventId) {
logger.error("Missing eventId option in showReportDialog call");
return;
}
if (!options.dsn) {
logger.error("Missing dsn option in showReportDialog call");
return;
}
var script = document.createElement('script');
script.async = true;
script.src = new API(options.dsn).getReportDialogEndpoint(options);
if (options.onLoad) {
// eslint-disable-next-line @typescript-eslint/unbound-method
script.onload = options.onLoad;
}
(document.head || document.body).appendChild(script);
}
//# sourceMappingURL=helpers.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/utils/esm/instrument.js
var instrument_global = (0,misc/* getGlobalObject */.Rf)();
/**
* Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.
* - Console API
* - Fetch API
* - XHR API
* - History API
* - DOM API (click/typing)
* - Error API
* - UnhandledRejection API
*/
var handlers = {};
var instrumented = {};
/** Instruments given API */
function instrument(type) {
if (instrumented[type]) {
return;
}
instrumented[type] = true;
switch (type) {
case 'console':
instrumentConsole();
break;
case 'dom':
instrumentDOM();
break;
case 'xhr':
instrumentXHR();
break;
case 'fetch':
instrumentFetch();
break;
case 'history':
instrumentHistory();
break;
case 'error':
instrumentError();
break;
case 'unhandledrejection':
instrumentUnhandledRejection();
break;
default:
logger.warn('unknown instrumentation type:', type);
}
}
/**
* Add handler that will be called when given type of instrumentation triggers.
* Use at your own risk, this might break without changelog notice, only used internally.
* @hidden
*/
function addInstrumentationHandler(handler) {
if (!handler || typeof handler.type !== 'string' || typeof handler.callback !== 'function') {
return;
}
handlers[handler.type] = handlers[handler.type] || [];
handlers[handler.type].push(handler.callback);
instrument(handler.type);
}
/** JSDoc */
function triggerHandlers(type, data) {
var e_1, _a;
if (!type || !handlers[type]) {
return;
}
try {
for (var _b = __values(handlers[type] || []), _c = _b.next(); !_c.done; _c = _b.next()) {
var handler = _c.value;
try {
handler(data);
}
catch (e) {
logger.error("Error while triggering instrumentation handler.\nType: " + type + "\nName: " + getFunctionName(handler) + "\nError: " + e);
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
}
/** JSDoc */
function instrumentConsole() {
if (!('console' in instrument_global)) {
return;
}
['debug', 'info', 'warn', 'error', 'log', 'assert'].forEach(function (level) {
if (!(level in instrument_global.console)) {
return;
}
fill(instrument_global.console, level, function (originalConsoleLevel) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
triggerHandlers('console', { args: args, level: level });
// this fails for some browsers. :(
if (originalConsoleLevel) {
Function.prototype.apply.call(originalConsoleLevel, instrument_global.console, args);
}
};
});
});
}
/** JSDoc */
function instrumentFetch() {
if (!supportsNativeFetch()) {
return;
}
fill(instrument_global, 'fetch', function (originalFetch) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var handlerData = {
args: args,
fetchData: {
method: getFetchMethod(args),
url: getFetchUrl(args),
},
startTimestamp: Date.now(),
};
triggerHandlers('fetch', tslib_es6_assign({}, handlerData));
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return originalFetch.apply(instrument_global, args).then(function (response) {
triggerHandlers('fetch', tslib_es6_assign(tslib_es6_assign({}, handlerData), { endTimestamp: Date.now(), response: response }));
return response;
}, function (error) {
triggerHandlers('fetch', tslib_es6_assign(tslib_es6_assign({}, handlerData), { endTimestamp: Date.now(), error: error }));
// NOTE: If you are a Sentry user, and you are seeing this stack frame,
// it means the sentry.javascript SDK caught an error invoking your application code.
// This is expected behavior and NOT indicative of a bug with sentry.javascript.
throw error;
});
};
});
}
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/** Extract `method` from fetch call arguments */
function getFetchMethod(fetchArgs) {
if (fetchArgs === void 0) { fetchArgs = []; }
if ('Request' in instrument_global && isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) {
return String(fetchArgs[0].method).toUpperCase();
}
if (fetchArgs[1] && fetchArgs[1].method) {
return String(fetchArgs[1].method).toUpperCase();
}
return 'GET';
}
/** Extract `url` from fetch call arguments */
function getFetchUrl(fetchArgs) {
if (fetchArgs === void 0) { fetchArgs = []; }
if (typeof fetchArgs[0] === 'string') {
return fetchArgs[0];
}
if ('Request' in instrument_global && isInstanceOf(fetchArgs[0], Request)) {
return fetchArgs[0].url;
}
return String(fetchArgs[0]);
}
/* eslint-enable @typescript-eslint/no-unsafe-member-access */
/** JSDoc */
function instrumentXHR() {
if (!('XMLHttpRequest' in instrument_global)) {
return;
}
// Poor man's implementation of ES6 `Map`, tracking and keeping in sync key and value separately.
var requestKeys = [];
var requestValues = [];
var xhrproto = XMLHttpRequest.prototype;
fill(xhrproto, 'open', function (originalOpen) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// eslint-disable-next-line @typescript-eslint/no-this-alias
var xhr = this;
var url = args[1];
xhr.__sentry_xhr__ = {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
method: isString(args[0]) ? args[0].toUpperCase() : args[0],
url: args[1],
};
// if Sentry key appears in URL, don't capture it as a request
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (isString(url) && xhr.__sentry_xhr__.method === 'POST' && url.match(/sentry_key/)) {
xhr.__sentry_own_request__ = true;
}
var onreadystatechangeHandler = function () {
if (xhr.readyState === 4) {
try {
// touching statusCode in some platforms throws
// an exception
if (xhr.__sentry_xhr__) {
xhr.__sentry_xhr__.status_code = xhr.status;
}
}
catch (e) {
/* do nothing */
}
try {
var requestPos = requestKeys.indexOf(xhr);
if (requestPos !== -1) {
// Make sure to pop both key and value to keep it in sync.
requestKeys.splice(requestPos);
var args_1 = requestValues.splice(requestPos)[0];
if (xhr.__sentry_xhr__ && args_1[0] !== undefined) {
xhr.__sentry_xhr__.body = args_1[0];
}
}
}
catch (e) {
/* do nothing */
}
triggerHandlers('xhr', {
args: args,
endTimestamp: Date.now(),
startTimestamp: Date.now(),
xhr: xhr,
});
}
};
if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') {
fill(xhr, 'onreadystatechange', function (original) {
return function () {
var readyStateArgs = [];
for (var _i = 0; _i < arguments.length; _i++) {
readyStateArgs[_i] = arguments[_i];
}
onreadystatechangeHandler();
return original.apply(xhr, readyStateArgs);
};
});
}
else {
xhr.addEventListener('readystatechange', onreadystatechangeHandler);
}
return originalOpen.apply(xhr, args);
};
});
fill(xhrproto, 'send', function (originalSend) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
requestKeys.push(this);
requestValues.push(args);
triggerHandlers('xhr', {
args: args,
startTimestamp: Date.now(),
xhr: this,
});
return originalSend.apply(this, args);
};
});
}
var lastHref;
/** JSDoc */
function instrumentHistory() {
if (!supportsHistory()) {
return;
}
var oldOnPopState = instrument_global.onpopstate;
instrument_global.onpopstate = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var to = instrument_global.location.href;
// keep track of the current URL state, as we always receive only the updated state
var from = lastHref;
lastHref = to;
triggerHandlers('history', {
from: from,
to: to,
});
if (oldOnPopState) {
return oldOnPopState.apply(this, args);
}
};
/** @hidden */
function historyReplacementFunction(originalHistoryFunction) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var url = args.length > 2 ? args[2] : undefined;
if (url) {
// coerce to string (this is what pushState does)
var from = lastHref;
var to = String(url);
// keep track of the current URL state, as we always receive only the updated state
lastHref = to;
triggerHandlers('history', {
from: from,
to: to,
});
}
return originalHistoryFunction.apply(this, args);
};
}
fill(instrument_global.history, 'pushState', historyReplacementFunction);
fill(instrument_global.history, 'replaceState', historyReplacementFunction);
}
/** JSDoc */
function instrumentDOM() {
if (!('document' in instrument_global)) {
return;
}
// Capture breadcrumbs from any click that is unhandled / bubbled up all the way
// to the document. Do this before we instrument addEventListener.
instrument_global.document.addEventListener('click', domEventHandler('click', triggerHandlers.bind(null, 'dom')), false);
instrument_global.document.addEventListener('keypress', keypressEventHandler(triggerHandlers.bind(null, 'dom')), false);
// After hooking into document bubbled up click and keypresses events, we also hook into user handled click & keypresses.
['EventTarget', 'Node'].forEach(function (target) {
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
var proto = instrument_global[target] && instrument_global[target].prototype;
// eslint-disable-next-line no-prototype-builtins
if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {
return;
}
/* eslint-enable @typescript-eslint/no-unsafe-member-access */
fill(proto, 'addEventListener', function (original) {
return function (eventName, fn, options) {
if (fn && fn.handleEvent) {
if (eventName === 'click') {
fill(fn, 'handleEvent', function (innerOriginal) {
return function (event) {
domEventHandler('click', triggerHandlers.bind(null, 'dom'))(event);
return innerOriginal.call(this, event);
};
});
}
if (eventName === 'keypress') {
fill(fn, 'handleEvent', function (innerOriginal) {
return function (event) {
keypressEventHandler(triggerHandlers.bind(null, 'dom'))(event);
return innerOriginal.call(this, event);
};
});
}
}
else {
if (eventName === 'click') {
domEventHandler('click', triggerHandlers.bind(null, 'dom'), true)(this);
}
if (eventName === 'keypress') {
keypressEventHandler(triggerHandlers.bind(null, 'dom'))(this);
}
}
return original.call(this, eventName, fn, options);
};
});
fill(proto, 'removeEventListener', function (original) {
return function (eventName, fn, options) {
try {
original.call(this, eventName, fn.__sentry_wrapped__, options);
}
catch (e) {
// ignore, accessing __sentry_wrapped__ will throw in some Selenium environments
}
return original.call(this, eventName, fn, options);
};
});
});
}
var debounceDuration = 1000;
var debounceTimer = 0;
var keypressTimeout;
var lastCapturedEvent;
/**
* Wraps addEventListener to capture UI breadcrumbs
* @param name the event name (e.g. "click")
* @param handler function that will be triggered
* @param debounce decides whether it should wait till another event loop
* @returns wrapped breadcrumb events handler
* @hidden
*/
function domEventHandler(name, handler, debounce) {
if (debounce === void 0) { debounce = false; }
return function (event) {
// reset keypress timeout; e.g. triggering a 'click' after
// a 'keypress' will reset the keypress debounce so that a new
// set of keypresses can be recorded
keypressTimeout = undefined;
// It's possible this handler might trigger multiple times for the same
// event (e.g. event propagation through node ancestors). Ignore if we've
// already captured the event.
if (!event || lastCapturedEvent === event) {
return;
}
lastCapturedEvent = event;
if (debounceTimer) {
clearTimeout(debounceTimer);
}
if (debounce) {
debounceTimer = setTimeout(function () {
handler({ event: event, name: name });
});
}
else {
handler({ event: event, name: name });
}
};
}
/**
* Wraps addEventListener to capture keypress UI events
* @param handler function that will be triggered
* @returns wrapped keypress events handler
* @hidden
*/
function keypressEventHandler(handler) {
// TODO: if somehow user switches keypress target before
// debounce timeout is triggered, we will only capture
// a single breadcrumb from the FIRST target (acceptable?)
return function (event) {
var target;
try {
target = event.target;
}
catch (e) {
// just accessing event properties can throw an exception in some rare circumstances
// see: https://github.com/getsentry/raven-js/issues/838
return;
}
var tagName = target && target.tagName;
// only consider keypress events on actual input elements
// this will disregard keypresses targeting body (e.g. tabbing
// through elements, hotkeys, etc)
if (!tagName || (tagName !== 'INPUT' && tagName !== 'TEXTAREA' && !target.isContentEditable)) {
return;
}
// record first keypress in a series, but ignore subsequent
// keypresses until debounce clears
if (!keypressTimeout) {
domEventHandler('input', handler)(event);
}
clearTimeout(keypressTimeout);
keypressTimeout = setTimeout(function () {
keypressTimeout = undefined;
}, debounceDuration);
};
}
var _oldOnErrorHandler = null;
/** JSDoc */
function instrumentError() {
_oldOnErrorHandler = instrument_global.onerror;
instrument_global.onerror = function (msg, url, line, column, error) {
triggerHandlers('error', {
column: column,
error: error,
line: line,
msg: msg,
url: url,
});
if (_oldOnErrorHandler) {
// eslint-disable-next-line prefer-rest-params
return _oldOnErrorHandler.apply(this, arguments);
}
return false;
};
}
var _oldOnUnhandledRejectionHandler = null;
/** JSDoc */
function instrumentUnhandledRejection() {
_oldOnUnhandledRejectionHandler = instrument_global.onunhandledrejection;
instrument_global.onunhandledrejection = function (e) {
triggerHandlers('unhandledrejection', e);
if (_oldOnUnhandledRejectionHandler) {
// eslint-disable-next-line prefer-rest-params
return _oldOnUnhandledRejectionHandler.apply(this, arguments);
}
return true;
};
}
//# sourceMappingURL=instrument.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/integrations/breadcrumbs.js
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable max-lines */
/**
* Default Breadcrumbs instrumentations
* TODO: Deprecated - with v6, this will be renamed to `Instrument`
*/
var Breadcrumbs = /** @class */ (function () {
/**
* @inheritDoc
*/
function Breadcrumbs(options) {
/**
* @inheritDoc
*/
this.name = Breadcrumbs.id;
this._options = tslib_es6_assign({ console: true, dom: true, fetch: true, history: true, sentry: true, xhr: true }, options);
}
/**
* Create a breadcrumb of `sentry` from the events themselves
*/
Breadcrumbs.prototype.addSentryBreadcrumb = function (event) {
if (!this._options.sentry) {
return;
}
hub_getCurrentHub().addBreadcrumb({
category: "sentry." + (event.type === 'transaction' ? 'transaction' : 'event'),
event_id: event.event_id,
level: event.level,
message: (0,misc/* getEventDescription */.jH)(event),
}, {
event: event,
});
};
/**
* Instrument browser built-ins w/ breadcrumb capturing
* - Console API
* - DOM API (click/typing)
* - XMLHttpRequest API
* - Fetch API
* - History API
*/
Breadcrumbs.prototype.setupOnce = function () {
var _this = this;
if (this._options.console) {
addInstrumentationHandler({
callback: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
_this._consoleBreadcrumb.apply(_this, tslib_es6_spread(args));
},
type: 'console',
});
}
if (this._options.dom) {
addInstrumentationHandler({
callback: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
_this._domBreadcrumb.apply(_this, tslib_es6_spread(args));
},
type: 'dom',
});
}
if (this._options.xhr) {
addInstrumentationHandler({
callback: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
_this._xhrBreadcrumb.apply(_this, tslib_es6_spread(args));
},
type: 'xhr',
});
}
if (this._options.fetch) {
addInstrumentationHandler({
callback: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
_this._fetchBreadcrumb.apply(_this, tslib_es6_spread(args));
},
type: 'fetch',
});
}
if (this._options.history) {
addInstrumentationHandler({
callback: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
_this._historyBreadcrumb.apply(_this, tslib_es6_spread(args));
},
type: 'history',
});
}
};
/**
* Creates breadcrumbs from console API calls
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Breadcrumbs.prototype._consoleBreadcrumb = function (handlerData) {
var breadcrumb = {
category: 'console',
data: {
arguments: handlerData.args,
logger: 'console',
},
level: Severity.fromString(handlerData.level),
message: safeJoin(handlerData.args, ' '),
};
if (handlerData.level === 'assert') {
if (handlerData.args[0] === false) {
breadcrumb.message = "Assertion failed: " + (safeJoin(handlerData.args.slice(1), ' ') || 'console.assert');
breadcrumb.data.arguments = handlerData.args.slice(1);
}
else {
// Don't capture a breadcrumb for passed assertions
return;
}
}
hub_getCurrentHub().addBreadcrumb(breadcrumb, {
input: handlerData.args,
level: handlerData.level,
});
};
/**
* Creates breadcrumbs from DOM API calls
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Breadcrumbs.prototype._domBreadcrumb = function (handlerData) {
var target;
// Accessing event.target can throw (see getsentry/raven-js#838, #768)
try {
target = handlerData.event.target
? htmlTreeAsString(handlerData.event.target)
: htmlTreeAsString(handlerData.event);
}
catch (e) {
target = '';
}
if (target.length === 0) {
return;
}
hub_getCurrentHub().addBreadcrumb({
category: "ui." + handlerData.name,
message: target,
}, {
event: handlerData.event,
name: handlerData.name,
});
};
/**
* Creates breadcrumbs from XHR API calls
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Breadcrumbs.prototype._xhrBreadcrumb = function (handlerData) {
if (handlerData.endTimestamp) {
// We only capture complete, non-sentry requests
if (handlerData.xhr.__sentry_own_request__) {
return;
}
var _a = handlerData.xhr.__sentry_xhr__ || {}, method = _a.method, url = _a.url, status_code = _a.status_code, body = _a.body;
hub_getCurrentHub().addBreadcrumb({
category: 'xhr',
data: {
method: method,
url: url,
status_code: status_code,
},
type: 'http',
}, {
xhr: handlerData.xhr,
input: body,
});
return;
}
};
/**
* Creates breadcrumbs from fetch API calls
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Breadcrumbs.prototype._fetchBreadcrumb = function (handlerData) {
// We only capture complete fetch requests
if (!handlerData.endTimestamp) {
return;
}
if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {
// We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)
return;
}
if (handlerData.error) {
hub_getCurrentHub().addBreadcrumb({
category: 'fetch',
data: handlerData.fetchData,
level: Severity.Error,
type: 'http',
}, {
data: handlerData.error,
input: handlerData.args,
});
}
else {
hub_getCurrentHub().addBreadcrumb({
category: 'fetch',
data: tslib_es6_assign(tslib_es6_assign({}, handlerData.fetchData), { status_code: handlerData.response.status }),
type: 'http',
}, {
input: handlerData.args,
response: handlerData.response,
});
}
};
/**
* Creates breadcrumbs from history API calls
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Breadcrumbs.prototype._historyBreadcrumb = function (handlerData) {
var global = (0,misc/* getGlobalObject */.Rf)();
var from = handlerData.from;
var to = handlerData.to;
var parsedLoc = (0,misc/* parseUrl */.en)(global.location.href);
var parsedFrom = (0,misc/* parseUrl */.en)(from);
var parsedTo = (0,misc/* parseUrl */.en)(to);
// Initial pushState doesn't provide `from` information
if (!parsedFrom.path) {
parsedFrom = parsedLoc;
}
// Use only the path component of the URL if the URL matches the current
// document (almost all the time when using pushState)
if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {
to = parsedTo.relative;
}
if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {
from = parsedFrom.relative;
}
hub_getCurrentHub().addBreadcrumb({
category: 'navigation',
data: {
from: from,
to: to,
},
});
};
/**
* @inheritDoc
*/
Breadcrumbs.id = 'Breadcrumbs';
return Breadcrumbs;
}());
//# sourceMappingURL=breadcrumbs.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/version.js
var SDK_NAME = 'sentry.javascript.browser';
var SDK_VERSION = '5.30.0';
//# sourceMappingURL=version.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/client.js
/**
* The Sentry Browser SDK Client.
*
* @see BrowserOptions for documentation on configuration options.
* @see SentryClient for usage documentation.
*/
var BrowserClient = /** @class */ (function (_super) {
__extends(BrowserClient, _super);
/**
* Creates a new Browser SDK instance.
*
* @param options Configuration options for this SDK.
*/
function BrowserClient(options) {
if (options === void 0) { options = {}; }
return _super.call(this, BrowserBackend, options) || this;
}
/**
* Show a report dialog to the user to send feedback to a specific event.
*
* @param options Set individual options for the dialog
*/
BrowserClient.prototype.showReportDialog = function (options) {
if (options === void 0) { options = {}; }
// doesn't work without a document (React Native)
var document = (0,misc/* getGlobalObject */.Rf)().document;
if (!document) {
return;
}
if (!this._isEnabled()) {
logger.error('Trying to call showReportDialog with Sentry Client disabled');
return;
}
injectReportDialog(tslib_es6_assign(tslib_es6_assign({}, options), { dsn: options.dsn || this.getDsn() }));
};
/**
* @inheritDoc
*/
BrowserClient.prototype._prepareEvent = function (event, scope, hint) {
event.platform = event.platform || 'javascript';
event.sdk = tslib_es6_assign(tslib_es6_assign({}, event.sdk), { name: SDK_NAME, packages: tslib_es6_spread(((event.sdk && event.sdk.packages) || []), [
{
name: 'npm:@sentry/browser',
version: SDK_VERSION,
},
]), version: SDK_VERSION });
return _super.prototype._prepareEvent.call(this, event, scope, hint);
};
/**
* @inheritDoc
*/
BrowserClient.prototype._sendEvent = function (event) {
var integration = this.getIntegration(Breadcrumbs);
if (integration) {
integration.addSentryBreadcrumb(event);
}
_super.prototype._sendEvent.call(this, event);
};
return BrowserClient;
}(BaseClient));
//# sourceMappingURL=client.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/integrations/trycatch.js
var DEFAULT_EVENT_TARGET = [
'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',
];
/** Wrap timer functions and event targets to catch errors and provide better meta data */
var TryCatch = /** @class */ (function () {
/**
* @inheritDoc
*/
function TryCatch(options) {
/**
* @inheritDoc
*/
this.name = TryCatch.id;
this._options = tslib_es6_assign({ XMLHttpRequest: true, eventTarget: true, requestAnimationFrame: true, setInterval: true, setTimeout: true }, options);
}
/**
* Wrap timer functions and event targets to catch errors
* and provide better metadata.
*/
TryCatch.prototype.setupOnce = function () {
var global = (0,misc/* getGlobalObject */.Rf)();
if (this._options.setTimeout) {
fill(global, 'setTimeout', this._wrapTimeFunction.bind(this));
}
if (this._options.setInterval) {
fill(global, 'setInterval', this._wrapTimeFunction.bind(this));
}
if (this._options.requestAnimationFrame) {
fill(global, 'requestAnimationFrame', this._wrapRAF.bind(this));
}
if (this._options.XMLHttpRequest && 'XMLHttpRequest' in global) {
fill(XMLHttpRequest.prototype, 'send', this._wrapXHR.bind(this));
}
if (this._options.eventTarget) {
var eventTarget = Array.isArray(this._options.eventTarget) ? this._options.eventTarget : DEFAULT_EVENT_TARGET;
eventTarget.forEach(this._wrapEventTarget.bind(this));
}
};
/** JSDoc */
TryCatch.prototype._wrapTimeFunction = function (original) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var originalCallback = args[0];
args[0] = wrap(originalCallback, {
mechanism: {
data: { function: getFunctionName(original) },
handled: true,
type: 'instrument',
},
});
return original.apply(this, args);
};
};
/** JSDoc */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TryCatch.prototype._wrapRAF = function (original) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return function (callback) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return original.call(this, wrap(callback, {
mechanism: {
data: {
function: 'requestAnimationFrame',
handler: getFunctionName(original),
},
handled: true,
type: 'instrument',
},
}));
};
};
/** JSDoc */
TryCatch.prototype._wrapEventTarget = function (target) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var global = (0,misc/* getGlobalObject */.Rf)();
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
var proto = global[target] && global[target].prototype;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {
return;
}
fill(proto, 'addEventListener', function (original) {
return function (eventName, fn, options) {
try {
if (typeof fn.handleEvent === 'function') {
fn.handleEvent = wrap(fn.handleEvent.bind(fn), {
mechanism: {
data: {
function: 'handleEvent',
handler: getFunctionName(fn),
target: target,
},
handled: true,
type: 'instrument',
},
});
}
}
catch (err) {
// can sometimes get 'Permission denied to access property "handle Event'
}
return original.call(this, eventName,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
wrap(fn, {
mechanism: {
data: {
function: 'addEventListener',
handler: getFunctionName(fn),
target: target,
},
handled: true,
type: 'instrument',
},
}), options);
};
});
fill(proto, 'removeEventListener', function (originalRemoveEventListener) {
return function (eventName, fn, options) {
var _a;
/**
* There are 2 possible scenarios here:
*
* 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified
* method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function
* as a pass-through, and call original `removeEventListener` with it.
*
* 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using
* our wrapped version of `addEventListener`, which internally calls `wrap` helper.
* This helper "wraps" whole callback inside a try/catch statement, and attached appropriate metadata to it,
* in order for us to make a distinction between wrapped/non-wrapped functions possible.
* If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.
*
* When someone adds a handler prior to initialization, and then do it again, but after,
* then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible
* to get rid of the initial handler and it'd stick there forever.
*/
var wrappedEventHandler = fn;
try {
var originalEventHandler = (_a = wrappedEventHandler) === null || _a === void 0 ? void 0 : _a.__sentry_wrapped__;
if (originalEventHandler) {
originalRemoveEventListener.call(this, eventName, originalEventHandler, options);
}
}
catch (e) {
// ignore, accessing __sentry_wrapped__ will throw in some Selenium environments
}
return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);
};
});
};
/** JSDoc */
TryCatch.prototype._wrapXHR = function (originalSend) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// eslint-disable-next-line @typescript-eslint/no-this-alias
var xhr = this;
var xmlHttpRequestProps = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];
xmlHttpRequestProps.forEach(function (prop) {
if (prop in xhr && typeof xhr[prop] === 'function') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fill(xhr, prop, function (original) {
var wrapOptions = {
mechanism: {
data: {
function: prop,
handler: getFunctionName(original),
},
handled: true,
type: 'instrument',
},
};
// If Instrument integration has been called before TryCatch, get the name of original function
if (original.__sentry_original__) {
wrapOptions.mechanism.data.handler = getFunctionName(original.__sentry_original__);
}
// Otherwise wrap directly
return wrap(original, wrapOptions);
});
}
});
return originalSend.apply(this, args);
};
};
/**
* @inheritDoc
*/
TryCatch.id = 'TryCatch';
return TryCatch;
}());
//# sourceMappingURL=trycatch.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/integrations/globalhandlers.js
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/** Global handlers */
var GlobalHandlers = /** @class */ (function () {
/** JSDoc */
function GlobalHandlers(options) {
/**
* @inheritDoc
*/
this.name = GlobalHandlers.id;
/** JSDoc */
this._onErrorHandlerInstalled = false;
/** JSDoc */
this._onUnhandledRejectionHandlerInstalled = false;
this._options = tslib_es6_assign({ onerror: true, onunhandledrejection: true }, options);
}
/**
* @inheritDoc
*/
GlobalHandlers.prototype.setupOnce = function () {
Error.stackTraceLimit = 50;
if (this._options.onerror) {
logger.log('Global Handler attached: onerror');
this._installGlobalOnErrorHandler();
}
if (this._options.onunhandledrejection) {
logger.log('Global Handler attached: onunhandledrejection');
this._installGlobalOnUnhandledRejectionHandler();
}
};
/** JSDoc */
GlobalHandlers.prototype._installGlobalOnErrorHandler = function () {
var _this = this;
if (this._onErrorHandlerInstalled) {
return;
}
addInstrumentationHandler({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
callback: function (data) {
var error = data.error;
var currentHub = hub_getCurrentHub();
var hasIntegration = currentHub.getIntegration(GlobalHandlers);
var isFailedOwnDelivery = error && error.__sentry_own_request__ === true;
if (!hasIntegration || shouldIgnoreOnError() || isFailedOwnDelivery) {
return;
}
var client = currentHub.getClient();
var event = isPrimitive(error)
? _this._eventFromIncompleteOnError(data.msg, data.url, data.line, data.column)
: _this._enhanceEventWithInitialFrame(eventFromUnknownInput(error, undefined, {
attachStacktrace: client && client.getOptions().attachStacktrace,
rejection: false,
}), data.url, data.line, data.column);
(0,misc/* addExceptionMechanism */.EG)(event, {
handled: false,
type: 'onerror',
});
currentHub.captureEvent(event, {
originalException: error,
});
},
type: 'error',
});
this._onErrorHandlerInstalled = true;
};
/** JSDoc */
GlobalHandlers.prototype._installGlobalOnUnhandledRejectionHandler = function () {
var _this = this;
if (this._onUnhandledRejectionHandlerInstalled) {
return;
}
addInstrumentationHandler({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
callback: function (e) {
var error = e;
// dig the object of the rejection out of known event types
try {
// PromiseRejectionEvents store the object of the rejection under 'reason'
// see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent
if ('reason' in e) {
error = e.reason;
}
// something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents
// to CustomEvents, moving the `promise` and `reason` attributes of the PRE into
// the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec
// see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and
// https://github.com/getsentry/sentry-javascript/issues/2380
else if ('detail' in e && 'reason' in e.detail) {
error = e.detail.reason;
}
}
catch (_oO) {
// no-empty
}
var currentHub = hub_getCurrentHub();
var hasIntegration = currentHub.getIntegration(GlobalHandlers);
var isFailedOwnDelivery = error && error.__sentry_own_request__ === true;
if (!hasIntegration || shouldIgnoreOnError() || isFailedOwnDelivery) {
return true;
}
var client = currentHub.getClient();
var event = isPrimitive(error)
? _this._eventFromRejectionWithPrimitive(error)
: eventFromUnknownInput(error, undefined, {
attachStacktrace: client && client.getOptions().attachStacktrace,
rejection: true,
});
event.level = Severity.Error;
(0,misc/* addExceptionMechanism */.EG)(event, {
handled: false,
type: 'onunhandledrejection',
});
currentHub.captureEvent(event, {
originalException: error,
});
return;
},
type: 'unhandledrejection',
});
this._onUnhandledRejectionHandlerInstalled = true;
};
/**
* This function creates a stack from an old, error-less onerror handler.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
GlobalHandlers.prototype._eventFromIncompleteOnError = function (msg, url, line, column) {
var ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
// If 'message' is ErrorEvent, get real message from inside
var message = isErrorEvent(msg) ? msg.message : msg;
var name;
if (isString(message)) {
var groups = message.match(ERROR_TYPES_RE);
if (groups) {
name = groups[1];
message = groups[2];
}
}
var event = {
exception: {
values: [
{
type: name || 'Error',
value: message,
},
],
},
};
return this._enhanceEventWithInitialFrame(event, url, line, column);
};
/**
* Create an event from a promise rejection where the `reason` is a primitive.
*
* @param reason: The `reason` property of the promise rejection
* @returns An Event object with an appropriate `exception` value
*/
GlobalHandlers.prototype._eventFromRejectionWithPrimitive = function (reason) {
return {
exception: {
values: [
{
type: 'UnhandledRejection',
// String() is needed because the Primitive type includes symbols (which can't be automatically stringified)
value: "Non-Error promise rejection captured with value: " + String(reason),
},
],
},
};
};
/** JSDoc */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
GlobalHandlers.prototype._enhanceEventWithInitialFrame = function (event, url, line, column) {
event.exception = event.exception || {};
event.exception.values = event.exception.values || [];
event.exception.values[0] = event.exception.values[0] || {};
event.exception.values[0].stacktrace = event.exception.values[0].stacktrace || {};
event.exception.values[0].stacktrace.frames = event.exception.values[0].stacktrace.frames || [];
var colno = isNaN(parseInt(column, 10)) ? undefined : column;
var lineno = isNaN(parseInt(line, 10)) ? undefined : line;
var filename = isString(url) && url.length > 0 ? url : (0,misc/* getLocationHref */.l4)();
if (event.exception.values[0].stacktrace.frames.length === 0) {
event.exception.values[0].stacktrace.frames.push({
colno: colno,
filename: filename,
function: '?',
in_app: true,
lineno: lineno,
});
}
return event;
};
/**
* @inheritDoc
*/
GlobalHandlers.id = 'GlobalHandlers';
return GlobalHandlers;
}());
//# sourceMappingURL=globalhandlers.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/integrations/linkederrors.js
var DEFAULT_KEY = 'cause';
var DEFAULT_LIMIT = 5;
/** Adds SDK info to an event. */
var LinkedErrors = /** @class */ (function () {
/**
* @inheritDoc
*/
function LinkedErrors(options) {
if (options === void 0) { options = {}; }
/**
* @inheritDoc
*/
this.name = LinkedErrors.id;
this._key = options.key || DEFAULT_KEY;
this._limit = options.limit || DEFAULT_LIMIT;
}
/**
* @inheritDoc
*/
LinkedErrors.prototype.setupOnce = function () {
addGlobalEventProcessor(function (event, hint) {
var self = hub_getCurrentHub().getIntegration(LinkedErrors);
if (self) {
return self._handler(event, hint);
}
return event;
});
};
/**
* @inheritDoc
*/
LinkedErrors.prototype._handler = function (event, hint) {
if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {
return event;
}
var linkedErrors = this._walkErrorTree(hint.originalException, this._key);
event.exception.values = tslib_es6_spread(linkedErrors, event.exception.values);
return event;
};
/**
* @inheritDoc
*/
LinkedErrors.prototype._walkErrorTree = function (error, key, stack) {
if (stack === void 0) { stack = []; }
if (!isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) {
return stack;
}
var stacktrace = computeStackTrace(error[key]);
var exception = exceptionFromStacktrace(stacktrace);
return this._walkErrorTree(error[key], key, tslib_es6_spread([exception], stack));
};
/**
* @inheritDoc
*/
LinkedErrors.id = 'LinkedErrors';
return LinkedErrors;
}());
//# sourceMappingURL=linkederrors.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/integrations/useragent.js
var useragent_global = (0,misc/* getGlobalObject */.Rf)();
/** UserAgent */
var UserAgent = /** @class */ (function () {
function UserAgent() {
/**
* @inheritDoc
*/
this.name = UserAgent.id;
}
/**
* @inheritDoc
*/
UserAgent.prototype.setupOnce = function () {
addGlobalEventProcessor(function (event) {
var _a, _b, _c;
if (hub_getCurrentHub().getIntegration(UserAgent)) {
// if none of the information we want exists, don't bother
if (!useragent_global.navigator && !useragent_global.location && !useragent_global.document) {
return event;
}
// grab as much info as exists and add it to the event
var url = ((_a = event.request) === null || _a === void 0 ? void 0 : _a.url) || ((_b = useragent_global.location) === null || _b === void 0 ? void 0 : _b.href);
var referrer = (useragent_global.document || {}).referrer;
var userAgent = (useragent_global.navigator || {}).userAgent;
var headers = tslib_es6_assign(tslib_es6_assign(tslib_es6_assign({}, (_c = event.request) === null || _c === void 0 ? void 0 : _c.headers), (referrer && { Referer: referrer })), (userAgent && { 'User-Agent': userAgent }));
var request = tslib_es6_assign(tslib_es6_assign({}, (url && { url: url })), { headers: headers });
return tslib_es6_assign(tslib_es6_assign({}, event), { request: request });
}
return event;
});
};
/**
* @inheritDoc
*/
UserAgent.id = 'UserAgent';
return UserAgent;
}());
//# sourceMappingURL=useragent.js.map
;// CONCATENATED MODULE: ./node_modules/@sentry/browser/esm/sdk.js
var defaultIntegrations = [
new InboundFilters(),
new FunctionToString(),
new TryCatch(),
new Breadcrumbs(),
new GlobalHandlers(),
new LinkedErrors(),
new UserAgent(),
];
/**
* The Sentry Browser SDK Client.
*
* To use this SDK, call the {@link init} function as early as possible when
* loading the web page. To set context information or send manual events, use
* the provided methods.
*
* @example
*
* ```
*
* import { init } from '@sentry/browser';
*
* init({
* dsn: '__DSN__',
* // ...
* });
* ```
*
* @example
* ```
*
* import { configureScope } from '@sentry/browser';
* configureScope((scope: Scope) => {
* scope.setExtra({ battery: 0.7 });
* scope.setTag({ user_mode: 'admin' });
* scope.setUser({ id: '4711' });
* });
* ```
*
* @example
* ```
*
* import { addBreadcrumb } from '@sentry/browser';
* addBreadcrumb({
* message: 'My Breadcrumb',
* // ...
* });
* ```
*
* @example
*
* ```
*
* import * as Sentry from '@sentry/browser';
* Sentry.captureMessage('Hello, world!');
* Sentry.captureException(new Error('Good bye'));
* Sentry.captureEvent({
* message: 'Manual',
* stacktrace: [
* // ...
* ],
* });
* ```
*
* @see {@link BrowserOptions} for documentation on configuration options.
*/
function init(options) {
if (options === void 0) { options = {}; }
if (options.defaultIntegrations === undefined) {
options.defaultIntegrations = defaultIntegrations;
}
if (options.release === undefined) {
var window_1 = (0,misc/* getGlobalObject */.Rf)();
// This supports the variable that sentry-webpack-plugin injects
if (window_1.SENTRY_RELEASE && window_1.SENTRY_RELEASE.id) {
options.release = window_1.SENTRY_RELEASE.id;
}
}
if (options.autoSessionTracking === undefined) {
options.autoSessionTracking = false;
}
initAndBind(BrowserClient, options);
if (options.autoSessionTracking) {
startSessionTracking();
}
}
/**
* Present the user with a report dialog.
*
* @param options Everything is optional, we try to fetch all info need from the global scope.
*/
function showReportDialog(options) {
if (options === void 0) { options = {}; }
if (!options.eventId) {
options.eventId = getCurrentHub().lastEventId();
}
var client = getCurrentHub().getClient();
if (client) {
client.showReportDialog(options);
}
}
/**
* This is the getter for lastEventId.
*
* @returns The last event id of a captured event.
*/
function lastEventId() {
return getCurrentHub().lastEventId();
}
/**
* This function is here to be API compatible with the loader.
* @hidden
*/
function forceLoad() {
// Noop
}
/**
* This function is here to be API compatible with the loader.
* @hidden
*/
function onLoad(callback) {
callback();
}
/**
* A promise that resolves when all current events have been sent.
* If you provide a timeout and the queue takes longer to drain the promise returns false.
*
* @param timeout Maximum time in ms the client should wait.
*/
function flush(timeout) {
var client = getCurrentHub().getClient();
if (client) {
return client.flush(timeout);
}
return SyncPromise.reject(false);
}
/**
* A promise that resolves when all current events have been sent.
* If you provide a timeout and the queue takes longer to drain the promise returns false.
*
* @param timeout Maximum time in ms the client should wait.
*/
function sdk_close(timeout) {
var client = getCurrentHub().getClient();
if (client) {
return client.close(timeout);
}
return SyncPromise.reject(false);
}
/**
* Wrap code within a try/catch block so the SDK is able to capture errors.
*
* @param fn A function to wrap.
*
* @returns The result of wrapped function call.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function sdk_wrap(fn) {
return internalWrap(fn)();
}
/**
* Enable automatic Session Tracking for the initial page load.
*/
function startSessionTracking() {
var window = (0,misc/* getGlobalObject */.Rf)();
var hub = hub_getCurrentHub();
/**
* We should be using `Promise.all([windowLoaded, firstContentfulPaint])` here,
* but, as always, it's not available in the IE10-11. Thanks IE.
*/
var loadResolved = document.readyState === 'complete';
var fcpResolved = false;
var possiblyEndSession = function () {
if (fcpResolved && loadResolved) {
hub.endSession();
}
};
var resolveWindowLoaded = function () {
loadResolved = true;
possiblyEndSession();
window.removeEventListener('load', resolveWindowLoaded);
};
hub.startSession();
if (!loadResolved) {
// IE doesn't support `{ once: true }` for event listeners, so we have to manually
// attach and then detach it once completed.
window.addEventListener('load', resolveWindowLoaded);
}
try {
var po = new PerformanceObserver(function (entryList, po) {
entryList.getEntries().forEach(function (entry) {
if (entry.name === 'first-contentful-paint' && entry.startTime < firstHiddenTime_1) {
po.disconnect();
fcpResolved = true;
possiblyEndSession();
}
});
});
// There's no need to even attach this listener if `PerformanceObserver` constructor will fail,
// so we do it below here.
var firstHiddenTime_1 = document.visibilityState === 'hidden' ? 0 : Infinity;
document.addEventListener('visibilitychange', function (event) {
firstHiddenTime_1 = Math.min(firstHiddenTime_1, event.timeStamp);
}, { once: true });
po.observe({
type: 'paint',
buffered: true,
});
}
catch (e) {
fcpResolved = true;
possiblyEndSession();
}
}
//# sourceMappingURL=sdk.js.map
;// CONCATENATED MODULE: ./src/main.js
function sentryBeforeSend(event, hint) {
let regExp = new RegExp("[a-z]+-extension\:\/\/[^\/]+\/", 'gi');
event = replaceStringInObjectProperties(event, regExp, "extension://antitracker/");
if (false) {}
return event;
}
if (false) {} else {
init({
dsn: 'https://fc16e67b5548432e9f9d7ffa71bb6846@o4504802466004992.ingest.sentry.io/4504995704537088',
environment: "production",
release: "anti-tracker@1.5.0.38",
beforeSend: sentryBeforeSend
});
}
//Chrome imposes a limit of 800x600 for Extension popup windows
//https://ayastreb.me/chrome-extension-with-react/
//https://code.visualstudio.com/blogs/2016/02/23/introducing-chrome-debugger-for-vs-code
//https://developer.chrome.com/webstore/i18n
let startExtension = rulesMatchedDetails => {
log.warn('[dnr] startExtension rulesMatchedDetails: ' + JSON.stringify(rulesMatchedDetails, null, 4));
loadAndInitStoredState(storedState => {
chrome.tabs.query({
currentWindow: true,
lastFocusedWindow: true,
active: true
}, tabs => {
if (!tabs || !tabs.length) {
return;
}
const [activeTab] = tabs;
if (!activeTab) {
return;
}
let homeElement = /*#__PURE__*/react.createElement(Home, {
"rulesMatchedDetails": rulesMatchedDetails,
"currentTab": activeTab,
...storedState
});
let container = document.getElementById('root');
let root = (0,client/* createRoot */.s)(container);
root.render(homeElement);
});
});
};
if (scripts_compat.dnr.available) {
scripts_compat.dnr.declarativeNetRequest.getMatchedRules(null, rulesMatchedDetails => {
startExtension(rulesMatchedDetails);
});
} else {
startExtension(null);
}
})();
/******/ })()
;